ybce ybce - 1 year ago 87
Ajax Question

Javascript/PHP string equality

I'm running an AJAX call which has a success function which takes in a variable returned from the php page like so.


$.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");


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
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.

Answer Source

You're sending JSON, which means that you're sending the literal bytes:


Note the quotes in there. Your JS code either needs to decode the JSON, or compare the raw json itself:

 result = JSON.parse(html)
 if (result == "login")


 if (html == '"login"')   // note the quotes

A simple console.log(html) would have shown you what you're dealing with.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download