I'm using the following code to send Ajax request to a PHP file:
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;
}
});
The contents of the PHP file are:
<?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;
}
Strangely enough, if I make the first two statements in the PHP file to be echo "#"; return;
then I'm able to see the "Login successful" message. Otherwise, even when I send the correct query (verified in phpMyAdmin), I keep getting the error saying "Failed to send Ajax request".
Any idea what might be causing it?