我正在使用以下代码将Ajax请求发送到PHP文件:
var d = "email=" + email + "&password=" + password;
$.ajax({
url: "login/c_login_form.php",
data: d,
type: "POST",
success: function(str) {
if ( str === "#" ) { //# means success
alert("Login successful!");
return;
}
else {
//login failed
alert("Error logging in: " + str);
return;
}
},
error: function(obj) {
alert("Failed to send Ajax request.");
return;
}
});
PHP文件的内容是:
<?php
/*
*
* The controller file for login form
*
*/
if( isset( $_POST["email"] ) && isset( $_POST["password"] )) {
$email = $_POST["email"];
$password = $_POST["password"];
//load the config file to read settings
require_once($_SERVER['DOCUMENT_ROOT'] . '/hrms/lib/config.php');
//connect to database
$conn = mysqli_connect($db_host, $db_username, $db_password, $db_name);
if(!$conn) {
echo "Can't connect to database";
return;
}
//check if employee is active
$query = "SELECT employee.emp_id, role, is_active FROM employee INNER JOIN user ON employee.emp_id = user.emp_id WHERE email_bb = '{$email}' AND password = '{$password}'";
if( $query === FALSE ) {
echo "Failed to query database.";
return;
}
$result = mysqli_query($conn, $query);
if( $result === false ) {
echo "No such user exists. Please re-check login details.";
return;
}
$row = mysqli_fetch_assoc($result);
if( (count($row) > 0 ) and ($row['is_active'] == "0") ) {
echo "Employee not active anymore. Please contact HR.";
return;
}
if( count($row) === 3 ) {
//Everything looks okay. Process login now.
$emp_id = $row['emp_id'];
$role = $row['role'];
//close connection
mysqli_close($conn);
session_start();
$_SESSION['emp_id'] = $emp_id;
echo "#";
$path = $_SERVER['DOCUMENT_ROOT'] . '/hrms/dashboard.php?role={$role}';
header("Location://{path}");
die();
}
}
else {
echo "Error. POST is not set.";
return;
}
奇怪的是,如果我将PHP文件中的前两个语句设为echo "#"; return;
,那么我就能看到“登录成功”消息。否则,即使我发送了正确的查询(在phpMyAdmin中验证),我仍然会收到错误“无法发送Ajax请求”。
知道可能导致它的原因吗?
答案 0 :(得分:0)
发布回答以关闭此问题。问题确实与已发送的标头有关,因为我在同一个地方使用了echo
和header
功能。当我删除header
部分并从JavaScript执行重定向时,它按预期工作。