来自php的jquery ajax响应未定义

时间:2013-04-18 22:35:33

标签: php javascript jquery ajax

使用ajax获取表单时遇到问题需要获取php响应。 javascript似乎是正确的,因为如果我擦除login_ajax.php上的所有内容并仅使用以下内容

echo 'CORRECT' 
//or 
echo 'INCORRECT'

一旦我使用真正的PHP代码,ajax就不会从PHP获得任何响应。 如果我删除

,则更加奇怪
return false

从javascript然后提交表单,我确实看到在浏览器中的login_ajax.php上显示了CORRECT或INCORRECT。

HTML:

<form id="login" action='login_ajax.php' method="get">

    <label>Email: <input type="text" name="email" id="email" value="nano@nano.com"></label>
    <label>Password: <input type="text" name="password" id="password" value="x"></label>

    <input type="submit" value="login">
    <div id="straight_response">php response here</div>
    <div id="message">status</div>
</form>

PHP:

if (isset($_GET['password'])) {
    $email = $_GET['email'];
    $password = $_GET['password'];
    $stored_pass = "123";

    if ($password == $stored_pass) {
        echo "CORRECT";
    } else {
        echo "INCORRECT";
    }
}
//Javascript works when using one of the two lines below instead of the code above
//echo 'INCORRECT';
//echo 'CORRECT'

JAVASCRIPT:

$('#login').submit(function(){


var email;
    var password;

    email       = $('#email').val();
    password    = $('#password').val();

    var data = {};
    data.email  = email;
    data.password   = password;

    var options = {};
    options.dataType = 'text';
    options.type = 'get';
    options.url= 'login_ajax.php';
    options.success = function (response) {
    //  jQuery.trim(response);
        console.log(response.results);
        console.log(response.query);
        $('#always').text(response);

        if (response === 'CORRECT') {
            $('#message').text('you got it right');
            console.log("good combination");
        }
        else if (response === 'INCORRECT') {
            $('#message').text('sorry, try again');
            console.log("bad combination");
        }
    };

    $.ajax(options);
    return false;
});//#login function

1 个答案:

答案 0 :(得分:1)

天哪,我实际上花了40分钟试图理解你的问题,事实证明,你没有通过你从表格中收集的data PHP通过AJAX。

轻松修复,在拨打电话前添加此行:

options.data = data;

尽管如此the documentation states

  

通常无需直接调用此函数,因为$.get().load()等几个更高级别的替代方案可用并且更易于使用。

在你的情况下,我认为$.get()的效果一样好。 虽然你可能想看一下JerrySeeger在评论中所说的内容,看起来使用GET代码可能代表了一个巨大的安全漏洞,你也应该使用SSL。