如何使用Ajax登录表单

时间:2018-11-15 06:53:39

标签: javascript php mysql ajax

我目前正在PHP PDO中创建一个登录表单,并且正在使用ajax在屏幕上显示相关消息,例如

"Logging in..."
"Some input fields are empty"
"Your username is required"
"Your password is required"

诸如输入字段是否为空之类的验证工作正常,以及登录凭据似乎不正确的情况,但是当我使用正确的凭据登录时,我只收到消息"Logging in...",并且什么也没有发生,我什至不认为它设置会话。我还添加了一个令牌来防止CSRF,只是想知道我是否正确使用了它。

我不确定是什么原因导致我的代码无法继续登录。

我的Ajax脚本:

<script type='text/javascript'>
    $(document).ready(function () {

    var submitButton = $("#btn-login");


    submitButton.on('click', function (e) {
        e.preventDefault();

        // Get input field values of the contact form
        var loginFormInputs = $('#login-form :input'),
            userName = $('#txt_uname_email').val(),
            userPassword = $('#txt_password').val(),
            token = $('#token').val(),
            alertMessage = $('#login-alert-message');

        // Disable Inputs and display a loading message
        alertMessage.html('<p style="opacity: 1"><i class="fa fa-spinner fa-spin text-success"></i> Logging in..</p>');
        submitButton.html('<i class="fas fa-spinner fa-spin"></i>');
        loginFormInputs.prop("disabled", true);

        // Data to be sent to server
        var post_data = {
            'form': 'loginForm',
            'userName': userName,
            'userPassword': userPassword,
            'token': token
        };

        // Ajax post data to server
        $.post('./api', post_data, function (response) {


            // Load jsn data from server and output message
            if (response.type === 'error') {

                alertMessage.html('<p><i class="fa-lg far fa-times-circle text-danger"></i> ' + response.text + '</p>');
                submitButton.html('Login');
                loginFormInputs.prop("disabled", false);

            } else {

                alertMessage.html('<p><i class="fa-lg far fa-check-circle text-success"></i> ' + response.text + '</p>');
                submitButton.html('Login');
                window.location = "dashboard";

            }

        }, 'json');

    });

});
</script>

我在(class.user.php)中使用的登录功能api.php

public function doLogin($uname,$umail,$upass)
{
    try
    {
        $stmt = $this->conn->prepare("SELECT * FROM `settings` LIMIT 1");
        $stmt->execute();
        $mainten=$stmt->fetch(PDO::FETCH_ASSOC);
        $stmt = $this->conn->prepare("SELECT user_id, user_name, user_email, user_pass, status FROM users WHERE user_name=:uname OR user_email=:umail ");
        $stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
        $userRow=$stmt->fetch(PDO::FETCH_ASSOC);
        if($stmt->rowCount() == 1) 
        {
            if(password_verify($upass, $userRow['user_pass']))
            {
                session_regenerate_id(false);
                return ["correctPass"=>true, "banned"=> ($userRow['status']== 1) ? true : false, "maintenance"=> ($mainten["maintenance"]== 1) ? true : false];

            }
            else
            {
                return ["correctPass"=>false];
            }
        }
    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
    }
}

api.php:

 //include class.user.php here and set $login = new USER();
//set $uname, $umail, $upass, $token vars here


    if( $_POST && $_POST["form"] === 'loginForm' ) {



        // Use PHP To Detect An Ajax Request code is here

        // Checking if the $_POST vars well provided, Exit if there is one missing code is here


        // PHP validation for the fields required code is here

        $validation = $login->doLogin($uname,$umail,$upass);
        if($validation["correctPass"]){
            if($validation["maintenance"]){
                if (!in_array($uname, array('admin'))){
                    $output = json_encode(
                        array(
                            'type' => 'error',
                            'text' => 'Website under maintenance.'
                        ));
                    die($output);
                }
            }
            if($validation["banned"]){
                $output = json_encode(
                    array(
                        'type' => 'error',
                        'text' => 'User has been banned.'
                    ));
                die($output);
            }else{
                if(Token::check($_POST['token'])) {
                $stmtt = $login->runQuery("SELECT user_id FROM users WHERE user_name=:uname OR user_email=:umail ");
                $stmtt->execute(array(':uname'=>$uname, ':umail'=>$umail));
                $userRow=$stmtt->fetch(PDO::FETCH_ASSOC);
                $_SESSION['user_session'] = $userRow['user_id'];
                      $output = json_encode(
                array(
                    'type' => 'message',
                    'text' => 'Logged in successfully.'
                ));

                die($output);
                //$success = "Logged in successfully, redirecting..";
                //header( "refresh:3;url=ab" );
                //$login->redirect('dashboard');
                } else {
                    $output = json_encode(
                        array(
                            'type' => 'error',
                            'text' => 'Unexpected error occured.'
                        ));
                    die($output);
                }
            }
        }
        else{
            $output = json_encode(
                array(
                    'type' => 'error',
                    'text' => 'Incorrect username or password.'
                ));
            die($output);
        }

    }

0 个答案:

没有答案