I'm running an Ajax call which has a success function which takes in a variable returned from the PHP page like so.
Ajax:
$.ajax ({
type: "POST",
url: "loginrequest.php",
data: 'username=' + username + '&password=' +pass,
success: function(html){
console.log(html); // Returns login
console.log(typeof html); // Returns string
console.log(html === "login"); // Returns false
if(html === 'login'){
window.location.href = 'index.php';
}
else if(html === 'false'){
alert("login failed");
}
}
});
PHP:
if($count == 1){
$_SESSION['user'] = $myusername;
$return = "login";
echo json_encode($return);
}
else {
$return = "false";
echo json_encode($return);
}
As you can see, I'm trying to implement a simple login page and then redirect the user or display an alert depending on the outcome of the number of rows returned from my database query.
What I don't understand is this:
console.log(html); // Returns "login"
console.log(typeof html); // Returns string
console.log(html === "login"); // Returns false
I tried echo-ing without json_encode() and it still would give me the same results. I was using ==, but then I read that it's safer to use ===, so I switched to that, but it still won't return true.
console.log(html.trim() === "login");.trim()removes the additional whitespace which can be appended to the response when dealing with plain text. As an improvement, return JSON instead to avoid the problem entirely.json_encodeadds"to the string, so you actually have"login"with the quotes. Take a look: https://eval.in/600312var_dumpof the generated 'json' would've easily showed the problem ;)