通过jqXhr访问Ajax Call响应PHP

时间:2015-07-24 10:45:16

标签: javascript php jquery ajax

我在Jquery中使用Ajax调用来让用户登录到该网站。

JQUERY调用如下所示

$("#login-form").validate({
    submitHandler : function(form) {
        var request;
        // bind to the submit event of our form
        // lets select and cache all the fields
        var $inputs = $(form).find("input, select, button, textarea");
        // serialize the data in the form
        var serializedData = $(form).serialize();
        // lets disable the inputs for the duration of the ajax request
        $inputs.prop("disabled", true);
        $('#submit_btn_log').html('<img src="images/loader.gif" 
        style="height:20px"/> Please Wait...');

        // fire off the request to /form.php
        request = $.ajax({
                url: "social_login/login",
                type: "post",
                data: serializedData
        });
        // callback handler that will be called on success
        request.done(function (response, textStatus, jqXHR) {
                // log a message to the console
                //console.log("Hooray, it worked!");
                window.setTimeout(hide_modal, 1000);
                window.setTimeout(function()
                        {window.location.reload()},1000); 
                });
        // callback handler that will be called on failure
        request.fail(function (jqXHR, textStatus, errorThrown) {
                console.error("The following error occured: " + textStatus, 
                errorThrown);
        });
        // callback handler that will be called regardless
        // if the request failed or succeeded
        request.always(function () {
                // reenable the inputs
                $inputs.prop("disabled", false);
        });            
     }
});

验证凭据的PHP函数是:

function login( array $data )
{
    $_SESSION['logged_in'] = false;
    if( !empty( $data ) ){
        // Trim all the incoming data:
        $trimmed_data = array_map('trim', $data);           
        // escape variables for security
        $email = mysqli_real_escape_string( $this->_con,  
         $trimmed_data['email'] );
        $password = mysqli_real_escape_string( $this->_con,  
         $trimmed_data['password'] );

        if((!$email) || (!$password) ) {
            throw new Exception( LOGIN_FIELDS_MISSING );
        }
        $password = md5( $password );
        $query = "SELECT user_ids, names, emails, createds FROM users where 
         emails = '$email' and passwords = '$password' ";
        $result = mysqli_query($this->_con, $query);
        $data = mysqli_fetch_assoc($result);
        $count = mysqli_num_rows($result);
        if( $count >= 1){
            $_SESSION = $data;
            $_SESSION['logged_in'] = true;
            return true;
        }else{
            return false;
        }
    } else{
        return false;
    }
}

在这里,我面临的问题是,无论何时用户输入错误的凭据 request.done 中的警告(textStatus)都会成功,莫代尔关闭。

表示我无法验证用户是否输入了错误的凭据。在提供正确的凭证模式关闭和登录happpens。

如何在 .done 功能上按功能检查返回值。

1 个答案:

答案 0 :(得分:3)

试试这个例子

在你的php脚本中返回json

<?php
$json=['success'=>'','error'=>''];
//after some action
if(1){
$json['success']='ok';  
}else{
    $json['error']='Your error message!';   
}


echo json_encode($json);
?>

在JQuery中设置dataType json

$.ajax({
    url: '/path/to/file',
    type: 'POST',
    dataType: 'json',
    data: {param1: 'value1'},
})
.done(function(data) {
    if(data.success=='ok'){
    //close the dialog
    }else{
    //show errors
alert(data.error);
or console.log(data.error);
    }
})
.fail(function() {
    console.log("error");
})
.always(function() {
    console.log("complete");
});

这不是您问题的准确答案,但它可以帮助您理解我认为的过程!