chronixlol
chronixlol

Reputation: 29

JQuery AJAX response handling

Probably some simple derp but I just can't figure this out, I'm using almost identical code in a different solution and it works.

Javascript:

$('#drop').click(function(e) {
    e.preventDefault();
    $('#login').slideToggle(1000);
});

$('#sub').click(function(e) {
    e.preventDefault();
    $('#info').html('<img src="img/load.gif" />')
    $.post('login.php', {user: document.getElementById('user').value, pass: document.getElementById('pass').value}, function(response) {
        if (response == 'ok')
        {
            $('#login').slideUp(500);
            $('#info').html('');
            $('#joocy').html('<img src="img/load.gif" />').load('manage.php');
        }
        else if (response == 'error')
        {
            $('#info').html('Invalid user/pass');
        }
    });
});

PHP:

if ($row = mysql_fetch_array($result))
{
    echo 'ok';
}
else
{
    echo 'error';
}

Response is being sent back but the if-clause isn't catching it. typeof() returns string.

EDIT: else if (response === 'error ') // notice the space in the string

This works, can anyone explain why the space is appended to the returnstring?

SOLVED: There was a space after PHP closing tag. Thanks for your time everyone! :)

Upvotes: 3

Views: 575

Answers (3)

Rafay
Rafay

Reputation: 31043

may the additional space is added from the php side of the code, you can use trim

if($.trim(response)==='error')
{
 //
}

Upvotes: 0

VolkerK
VolkerK

Reputation: 96189

Maybe the output contains other characters like e.g. a BOM.
What does

$.post('login.php', {user: document.getElementById('user').value, pass: document.getElementById('pass').value}, function(response) {
    if (response == 'ok')
    {
        $('#login').slideUp(500);
        $('#info').html('');
        $('#joocy').html('<img src="img/load.gif" />').load('manage.php');
    }
    else if (response == 'error')
    {
        $('#info').html('Invalid user/pass');
    }
    var tmpText = "" + response.length + ": ";
    for(var tmpI=0; tmpI<response.length; tmpI++) {
        tmpText += response.charCodeAt(tmpI) + " ";
    }
    $("<fieldset></fieldset>").text(tmpText).appendTo("#info");
});

print?

Upvotes: 1

Corey Hart
Corey Hart

Reputation: 10616

You probably have a space after the closing '?>' tag in your php script. Try either removing all whitespace after, or the closing tag altogether.

Upvotes: 2

Related Questions