0

I am returning a string form php and compare it with another string in jQuery. I am 100% certain that the strings do match (well, at least are of the same value...), but still my if-clause thinks otherwise.

This is the part of my php-script that sets the returning value:

if (!$result){
        echo "false";
        exit();
    }

This is my jQuery that performs the matching:

$.post("registeraccount.php",$(this).serialize(),function(msg){
        //alert the response from the server
        alert(msg + " = " + (msg == "false"));
        if(msg == "false"){
            $("#adminarea").html("Error");

        }else{
            $("#adminarea").html("Success");
        }

   });

No matter that the strings are equal or not equal, it's always "Success" that is printed on the web page.

In the alert I get the following result "false = false". Hence, (msg == "false") is false.

How come the strings are not true when they are equal and how do I fix it?

6
  • Are you sure 'msg' is a string? Commented Aug 7, 2011 at 7:23
  • 1
    Have you checked for stray whitespace in msg? Commented Aug 7, 2011 at 7:24
  • @silverstrike, doesn't 'echo "false"' imply that it is a string? Commented Aug 7, 2011 at 7:26
  • @mu is too short , how do I check for stray whitespace? Commented Aug 7, 2011 at 7:31
  • 1
    Not necessarily. The server echo the word false, but do you pass false or "false"? Commented Aug 7, 2011 at 7:33

2 Answers 2

4

I suppose that the reason is that msg, your server output, is never exactly "false", due to some line endings that are added or similar things in you PHP script (you could check if msg has the length you expect to verify this hypothesis). In this case, you could try using this:

 if (msg.match(/false/)) {

which does a somewhat less strict comparison if you want, ensuring that the output contains the string "false" (at any position). If it works, I suggest that you use instead this comparison:

 if (msg.match(/^false$/)) {

which guarantees that false be a whole line of your text.

Sign up to request clarification or add additional context in comments.

2 Comments

or if ($.trim(msg) == "false") { or if (msg.indexOf('false') > -1) {
@sergio, msg.match(/false/) worked but msg.match(/^false$/) didn't. Thanks!
-3

You have to use === to compare for equality in JavaScript.

If you have time have a look at Crockford video series on javascript. It covers this and a lot of other javascript topics.

1 Comment

Didn't work. I don't think it should be necesseary, should it? Googling around for comparing strings in javascript, most posts say "==".

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.