我正在尝试发出AJAX请求,将数据发送到PHP文件,检查用户名和密码是否正确,返回答案,然后运行确定运行会话的login.php文件。
现在,我的AJAX请求除了打印我整个登录页面的HTML代码外,什么都不做。
如果有人知道为什么,请告诉我...
(我为发布我的所有login.js和checkLogin.php表示歉意,我担心如果没有这两个上下文,问题可能无法回答)
这是login.js
$(function() { //Once the document has fully loaded
$("#login_form").submit(function(event) {
//INITIALIZING VARIABLES
var userName = $("#userName").val();
var passWord = $("#passWord").val();
var error = 0;
event.preventDefault(); //Prevent normal submit action
$("#userError, #passError").text(""); //Clear the text each time the user clicks submit
if (userName == "") { //Checking if the username is blank
$("#userError").text("Please enter your username");
error = 1;
}
if (passWord == "") { //Checking if the password is blank
$("#passError").text("Please enter your password");
error = 1;
}
//BEGIN Ajax Request
var $form = $(this),
term = $form.find("userName, passWord"),
url = 'checkLogin.php';
var posting = $.post(url, {username: userName, password: passWord});
posting.done(function(data) {
$("#userError").text(posting.responseText);
});
//END Ajax Request
if (error == 0) {
$("passError").text("Success");
}
}); //END submit button click
$("#login_form").submit();
});
这是checkLogin.php
<?php
$link = mysqli_connect(DB info private); //Database Connection
if (!$link) {
die('Could not connect: ' . mysqli_connect_error());
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') { //Keeps the text inside the this.responseText
//Preparing and Binding SQL statement
$stmt = mysqli_prepare($link, "SELECT username, password FROM login WHERE username =? and password =?");
mysqli_stmt_bind_param($stmt, "ss", $username, $password);
//PRINTS UNIDENTIFIED INDEX
$username = $_POST['username']; //Retrieving the username
$password = $_POST['password']; //Retrieving the password
mysqli_stmt_execute($stmt); //Execute the parameterized prepared statement
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
}
?>
client_login.php中的表单标记
<form action="login.php" method="post" name="login_form" id="login_form">
</form>
答案 0 :(得分:1)
您没有在checkLogin.php上返回任何内容。您应该尝试:
$row = mysqli_fetch_assoc($result);
if($row) {
echo "User found!";
exit();
}
我建议您,以json格式返回文本。这样,您可以返回更复杂的响应以在js脚本中使用。例如,在您的checkLogin.php中:
$row = mysqli_fetch_assoc($result);
if($row) {
echo json_encode([
'code' => '1', // code that represent successful
'message' => 'User found!'
]);
exit();
}
在您的login.js中:
posting.done(function(data) {
var response = JSON.parse(data);
if(response.code == '1') {
$("#userError").text(response.message);
}
});
答案 1 :(得分:1)
这里有几个问题
url = checkLogin.php;
应该是url = 'checkLogin.php';
现在,URL将是undefined
,而ajax url将把所有内容发布到yoursite.com/undefined
,显然,服务器将返回404,带有默认的404页面。这就是为什么您在响应中看到html的原因。
您的checkLogin.php
应该向客户端返回一些数据。为此使用echo()
。