13

I'm having a very hard time trying to do something very simple. Here's the code:

        if(data == 'success') {

            alert('foo');

        } else {

            alert(data);

        }

I've simplified it, but that's all that's necessary to understand what's going on. the variable 'data' is a result of an AJAX call, if that makes any difference. The problem is that it always goes to the 'else' statement and it alerts 'success', which it shouldn't if it goes to the 'else'. Any idea what's going on here?

EDIT: Here's the full AJAX code in jQuery:

$.post("/manage_sites.php", {before:before, edit:after}, function(data){

        if(data == success) {

            alert('blah');

        } else {
            alert(data);
        }
    });

And then in the PHP response:

...code....
$update = mysql_query("UPDATE users SET feeds = '$afterFeed' WHERE username = '$name'") or     die("Query Failed");

if($update) {

    echo  'success';  //this is the 'string' that is being given to 'data'
}
9
  • 2
    alert(typeof data); This will give you an idea if you are comparing apples to oranges, and thus always getting into the else. Commented Jul 13, 2010 at 0:53
  • 1
    can you paste the full ajax response, is it json? Commented Jul 13, 2010 at 0:59
  • What's data suppose to look like? 'success' as a string or XML as a string type? Commented Jul 13, 2010 at 0:59
  • Something else is going on. No pun intended ;) Commented Jul 13, 2010 at 0:59
  • 3
    is there a newline character after the success perhaps? try alert('x' + data + 'x') to see if there is anything else in that string Commented Jul 13, 2010 at 0:59

3 Answers 3

32

You can fix it on the client side using $.trim() like this:

if($.trim(data) == 'success') {

Or, a better approach would be removing the new-line coming from the server-side, probably an erroneous new-line in your PHP somewhere, check before or after the <? ?> block, this is most often where they crop up.

Or, just exit after outputting your content, like this:

if($update) {
  echo 'success';
  exit();
}
Sign up to request clarification or add additional context in comments.

1 Comment

I am reading the 'content' CSS property of an element and even trimming doesn't help the comparison to pass.
0

You can remove the trailing ?> in your file, if it is the last line in the file. I want to response to the comments to the original issue, but i don't see how.

1 Comment

You need 50 rep to post a comment on a question you didn't ask. Keep posting! stackoverflow.com/faq
0

Client side validation working fine.

$.trim() fine.

Thank You Nick. It took me long to understand why its not working ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.