Ajax不执行成功函数

时间:2015-03-18 06:15:08

标签: php jquery ajax ajaxform jquery-ajaxq

我有一个jquery ajax函数,它将表单数据提交到php文件,在该文件中对数据库进行检查并返回响应。但是我的成功函数没有被执行,而是通过错误函数返回响应。

以下是我的login.js代码:

$(document).ready(function(){
    $("form#loginForm").submit(function() { // loginForm is submitted
        var username = $('#username').attr('value'); // get username
        var password = $('#password').attr('value'); // get password

    if (username && password) { // values are not empty
        $.ajax({
            type: "POST",
            url: "url", // URL of the Php script
            contentType: "application/json; charset=utf-8",
            dataType: "json", //expected from server in response
            // send username and password to the Php script
            data: "username=" + username + "&password=" + password,


            error: function(XMLHttpRequest, textStatus, errorThrown) { // script call was *not* successful
                $('div#loginResult').text("responseText: " + XMLHttpRequest.responseText
                + ", textStatus: " + textStatus
                + ", errorThrown: " + errorThrown);
                $('div#loginResult').addClass("error");
            },

            success: function(data){ //script was successful, data contains response from mysql database
                if (data.error) { // login was not successful
                    $('div#loginResult').text("data.error: " + data.error);
                    $('div#loginResult').addClass("error");
                } // if
                else { // login was successful
                    $('form#loginForm').hide();
                    $('div#loginResult').text("data.success: " + data.success);
                    $('div#loginResult').addClass("success");
                } //else
            } // success
        }); // ajax
    } // if
    else {
        $('div#loginResult').text("enter username and password");
        $('div#loginResult').addClass("error");
    } // else
    $('div#loginResult').fadeIn();
    return false;
});
});

这是我的Login.php代码:

 <?php



$username = $_POST["username"];
$password = $_POST["password"];


$dbhost = '*****';
$dbuser = '*****';
$dbpass = '*****';
$conn = mysql_connect($dbhost, $dbuser, $dbpass); // connect to server
if(! $conn )
{
    die('Could not connect: ' . mysql_error());
}

echo 'Connected to database successfully,';

mysql_select_db('sl493',$conn); //pick sl493 database


$result = mysql_query("SELECT *
        FROM metauser
        WHERE metauser.username = '$username'
        AND metauser.password = '$password'") or die(mysql_error()); //select data from metauser table

$row = mysql_fetch_assoc($result);

if($row['username'] == $username) //If username and password not accepted
{$result = 'true login';
 $arr = array('success' => "login is successful");
 echo json_encode($arr);}

else //if username and password are not accepted
{$result = 'login failed';
 $arr = array('error' => "username or password is wrong");
 echo json_encode($arr);}

?>

现在,无论我输入正确或不正确的凭据,我都会收到以下回复:

responseText:已成功连接到数据库,{“”成功“:”登录成功“}  ,textStatus:parsererror,errorThrown:无效的JSON:成功连接到数据库,{“”成功“:”登录成功“} http://i.imgur.com/n1nZ2ac.jpg

它返回“已连接到数据库成功”,这意味着它成功进入login.php,但它也返回响应文本,这是ajax:error的一部分,它应该不会去,因为函数执行成功.HALP?

3 个答案:

答案 0 :(得分:1)

我想出了什么问题:

  1. 首先我将ContentType指定为json,而我将其作为a发送 字符串,所以我不得不改变它。

  2. 其次,我使用了$ _POST的Is_set andis_empty函数来制作 确定我收到了POST字段。

  3. 最后返回ajax变量数据,因为它不会显示它 按键,所以data.success未定义但数据返回所有输出 来自php文件。
  4. 我仍在试图找出为什么我无法通过密钥访问返回的JSON。如果您有任何建议,请告诉我,我不想再提出问题。以下是工作代码:

    $(document).ready(function(){
        $("form#loginForm").submit(function() {
    
        // loginForm is submitted
            var username = $('#username').attr('value'); // get username
            var password = $('#password').attr('value'); // get password
            console.log(username + password) ;
    
            if (username && password) { // values are not empty
                $.ajax({
                    type: "POST",
                    url: "https://xxx/login.php", // URL of the Php script
                    contentType: "application/x-www-form-urlencoded; charset=utf-8",
    
                    dataType: "application/json", //expected from server in response
                    // send username and password to the Php script
                    //data: "username=" + username + "&password=" + password,
                    data:'username='+ username+'&password='+ password,
    
                    error: function(XMLHttpRequest, textStatus, errorThrown) { // script call was *not* successful
                        $('div#loginResult').text("responseText: " + XMLHttpRequest.responseText
                        + ", textStatus: " + textStatus
                        + ", errorThrown: " + errorThrown);
                        $('div#loginResult').addClass("error");
                    },
    
                    success: function(data){
    
    
                        $('form#loginForm').hide();
                        $('div#loginResult').text("Login: " + data );
                        $('div#loginResult').addClass("success");
                                                                    }
    
    
                });
            }
            else {
                $('div#loginResult').text("enter username and password");
                $('div#loginResult').addClass("error");
            } // else
            $('div#loginResult').fadeIn();
            return false;
        });
    })
    

    的login.php

    <?php
    
    if (isset($_POST["username"]) && !empty($_POST["username"])) {
        $username = $_POST["username"];}
    
    if (isset($_POST["password"]) && !empty($_POST["password"])) {
        $password = $_POST["password"];}
    
    $dbhost = 'xxx';
    $dbuser = 'xxxxxx';
    $dbpass = 'xxxxxxxx';
    $conn = mysql_connect($dbhost, $dbuser, $dbpass); // connect to server
    if(! $conn )
    {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db('sl493',$conn);
    
    $query = mysql_query("SELECT *FROM metauser WHERE metauser.username = '$username'AND metauser.password = '$password'") or die(mysql_error()); //select data from metauser table
    $row = mysql_fetch_assoc($query);
    
    
    if($row['username'] == $username)
    {
            if($row['usertype']== 'student')
                  { $type = 'student'; }
                        else{ $type = 'admin'; }
    
        //$arr = array('result' => 'loginOK', 'usertype' => $type);
    
        $associativeArray = array();
        $associativeArray ['result'] = 'success';
        $associativeArray ['usertype'] = $type;
    
        //$arr = '{"success":"login is successful"}';
        //echo $type;
        echo json_encode($associativeArray); }
    
    
    else
    {$arr = '{"error":"username or password is wrong"}';
        echo json_encode($arr);}
    
    ?>
    

答案 1 :(得分:0)

试试这个:

var data="";
data=['username':username,'password':password];//Add this

 $.ajax({
            type: "POST",
            url: "url", // URL of the Php script
            contentType: "application/json; charset=utf-8",
            dataType: "json", //expected from server in response
            // send username and password to the Php script
            data: JSON.stringify(data),//Stringify your data while sending
            success: function(data){ //script was successful, data contains response from mysql database
                if (data.error) { // login was not successful
                    $('div#loginResult').text("data.error: " + data.error);
                    $('div#loginResult').addClass("error");
                } // if
                else { // login was successful
                    $('form#loginForm').hide();
                    $('div#loginResult').text("data.success: " + data.success);
                    $('div#loginResult').addClass("success");
                } //else
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) { // script call was *not* successful
                $('div#loginResult').text("responseText: " + XMLHttpRequest.responseText
                + ", textStatus: " + textStatus
                + ", errorThrown: " + errorThrown);
                $('div#loginResult').addClass("error");
            }, // success
        }); // ajax

答案 2 :(得分:0)

请将您的ajax数据类型从dataType: "json"更改为

datatype: "application/json"

要解决未经授权响应时的响应标头问题,请在代码的其他部分添加响应标头header('HTTP/1.1 401 Unauthorized', true, 401);,如下所示。

else //if username and password are not accepted
{$result = 'login failed';
 $arr = array('error' => "username or password is wrong");
header('HTTP/1.1 401 Unauthorized', true, 401);
 echo json_encode($arr);}