JohnWick
JohnWick

Reputation: 5149

JQuery string comparison returning incorrect value?

I am sending a post request to a PHP script via AJAX like so:

$.post("login.php", {u: username,p: password})
    .done(function(response){
        console.debug(response);
        if (response === "0") {
            $("#loginMessage").html("Invalid Username or Password");
        } else {
            $.mobile.changePage("#homePage");
        }
})

And login.php snippet. If the login credential fails, I am echoing "0". I believe this would output a string, since it is in quotes, as opposed to echo 0;

    if ($stmt->num_rows > 0 && password_verify($password,$hashedPassword)) {
        $_SESSION["uid"] = $uid;
    } else {
        echo "0";
    }

However, when I enter invalid credentials the comparison response === "0" is returning FALSE, although when I use console.debug(response), it is showing that it is indeed 0.

After some of my own fiddling, I found that if I change response === "0" to response == 0, it correctly evaluates to true.

response === 0 also evaluates to FALSE, which confuses me even more.

Can someone explain this a bit for me?

Upvotes: 2

Views: 88

Answers (2)

Yashar
Yashar

Reputation: 133

Strict equality Operator compares both value and data type. For example, if you compare zero as a string and zero as a number, it returns false. so that is why you see false. Make sure you compare 2 objects with the same type and data when you what to use "Strict equality" (===) otherwise use simple Equality operator (==).

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816452

A typical reason for this problem is that the response contains whitespace characters. They wouldn't necessarily be obvious in the console, but inspecting response.length is one easy way to find out.

Keep in mind that anything outside the <?php ... ?> delimiters, also whitespace characters (e.g. line breaks), will be included in the response.

A typical way to prevent trailing whitespace characters is to not have a closing ?> at all.


While you could simply "trim" the response before the comparison, the better solution is to fix the server side script to really just send what you want to send.

Upvotes: 1

Related Questions