Birrel
Birrel

Reputation: 4834

AJAX responseText missmatch

I have an AJAX call:

var ajax = new XMLHttpRequest();
ajax.open("POST", "testing.php", true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.onreadystatechange = function(){
    if(ajax.readyState == 4 && ajax.status == 200){
        var returnVal = ajax.responseText;

        if(returnVal == "success"){
            // Redirect
        }else{
            // Inform of failure
        }
    }
}
ajax.send("testing=1");

that pairs with the following PHP:

if(isset($_POST["testing"])){
    $formScore = checkForm($db_conx);
    if($formScore == 10){
        echo "success";
        exit();
    }else{
        echo "fail";
        exit();
    }
}

And this works just fine. The form score is "10" when it should be, and the value sent back to the AJAX call is, in fact, "success". At least, if I print out the response text:

$('.output').html(ajax.responseText);

the value in output is " success" - WITH the space preceding the word. I cannot select the space with my cursor, but it is there when I view the HTML for the page.

But, no matter what, the line if(returnVal == "success") always equates to false. I've even tried if(returnVal == " success"), but still false.

This is all the code. I've even tried hard-coding $formScore = 10; to see if that was the issue. Regardless, for some reason the equality always comes out false.

Is there something obvious I'm missing? I've tested this 100 different ways, and still the same result.

Upvotes: 0

Views: 65

Answers (2)

Sadikhasan
Sadikhasan

Reputation: 18600

You can use jQuery trim function to remove lading and trailing space.

if($.trim(returnVal) == "success")

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

There is a space somewhere in your PHP file which is causing this issue. Possibly at the start of the file before the <?php.

To work around this you could trim the response before you use it in the condition:

if (returnVal.trim() == "success") {

Or alternatively change your PHP to return JSON with the flag as a property, that way whitespace will not be an issue.

The best solution would obviously be to get rid of the space in your server-side code, however we can't diagnose that problem without seeing your PHP.

Upvotes: 2

Related Questions