Skip to content Skip to sidebar Skip to footer

Comparing Two Identical Strings In JQuery Returns False

I discovered an interesting problem with an echoed value from an AJAX request of JQuery, which I don't have an answere for: My data == 'LOCKED' never returns true (line 13)! JQuer

Solution 1:

Must be because of some white-spaces or new lines, it is always better to trim the data. Try this:

if (data.trim() == "LOCKED") {

You can also use:

if ($.trim(data) == "LOCKED") { // using jQuery.

Solution 2:

You can try JSON.parse. If value looks like "LOCKED" on console, it means its like ""LOCKED"".

Edit 1

As commented, you are getting "\r\nLOCKED" as stringified value, so you can use a regex to replace it. Following is the updated code.

Reference - How to remove all line breaks from a string?

Sample

var a = "LOCKED";
var strA = "\r\nLOCKED";
var regex = /\r?\n|\r/g;
var cleanStr = strA.replace(regex,'');
console.log(a);
console.log(strA);

console.log(strA == a);
console.log(cleanStr == a);

Solution 3:

Probably due to whitepace somewhere, such as a space before an opening php tag etc.

Far better to use a structured data format like json, and return a boolean propery to avoid these issues:

$result = $lih -> check($_POST["user"], $_POST["password"]);
$locked = ($result == 'LOCKED');
header('Content-Type: application/json');
echo json_encode(['locked'=>$locked]);

Javascript:

if(data.locked){ 

Post a Comment for "Comparing Two Identical Strings In JQuery Returns False"