ybce ybce - 1 year ago 46
Ajax Question

AJAX call not redirecting

I've implemented a login page with an AJAX request, that redirects the user depending on the response from the php page

loginrequest.php


$.ajax ({

type: "POST",
url: "ajax/loginrequest.php",
data: {
username: username,
password:pass
},

dataType: "text",

success: function(html){

console.log(html); // Prints 'login' or 'fail'

if(html == 'login'){
console.log("Yes"); //Never Printed
window.location.href = 'index.php';
}
else if(html == 'fail'){
alert("Incorrect Username and/or Password");
}
}


});`


This is the
loginrequest.php
code that echos
login
or
fail
back to the AJAX function

if($count == 1){
$bool = password_verify($mypassword, $row[1]);

if($bool == true){
$_SESSION['user'] = $myusername;
$_SESSION['division'] = $row[2];
$return = 'login';
}
else{
$return = 'fail';
}
}
else{
$return = 'fail';
}
echo $return;


The
console.log
inside my success function prints login or fail depending on the credentials, but for some reason the if statement never evaluates to true. My page never redirects and it never displays the alert no matter what. I just uploaded these files to the web server, and they were working fine on WAMP but for some reason it's not working anymore. I tried
json_encode()
in
loginrequest.php
but it still wouldn't work. There is nothing wrong with my database call since it returns login or fail depending on the credentials, it's just that if statement in the success function.

What am I doing wrong here?

Answer Source

It is very likely that you have a stray whitespace being echo'd by PHP

Try

success: function(html){

    console.log(html); // Prints 'login' or 'fail'

    console.log(html.length); // Is it 5 and 4 respectively?

    html = $.trim(html); // if a space is the issue then this should fix it

    if(html == 'login'){
        console.log("Yes"); //Never Printed
        window.location.href = 'index.php';
    }
    else if(html == 'fail'){
        alert("Incorrect Username and/or Password");
    }
}