I am using the below code for a log in screen that uses an ajax call to check the user creds via the PHP script. As you can see I have put in a console call in which works but the if call is being skipped every time.
UPDATE *** I have realised that when I send the response to the console it seems to be an empty line then the echo from the PHP script on a new line.
Ajax Call
$(document).ready(function(){
// Variable to hold request
var request;
// Bind to the submit event of our form
$("#log").submit(function(event){
// Prevent default posting of form
event.preventDefault();
// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
// Disable the inputs for the duration of the Ajax request.
$inputs.prop("disabled", true);
// Fire off the request
request = $.ajax({
url: "../php/auth.php",
type: "post",
data: serializedData
});
request.done(function (response){
console.log(response);
if (response == "ok") {
setTimeout(function() {
return window.location.href = "../drive.php";
}, 3000);
}
else {
$('#error').html('<p class="text-center">'+response+'</p>');
}
});
PHP Script
session_start();
include '***';
$email = clean($_POST['email']);
$pass = clean($_POST['pass']);
$_SESSION['name'] = $email;
$query = "SELECT * from users WHERE user='$email' and pass='$pass'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if ($count == 1) {
echo 'ok';
}
else {
echo 'Please Try Again';
};
The php script was sending back whitespace and a new line hence why even though the console was outputting the correct return string it wasn't satisfying the if statement.
The include at the top of my PHP script had two extra lines of white space after the ?> closing tag. After removing this the response is now correct and satisfying the if statement on the Ajax call.