Dan Hanly
Dan Hanly

Reputation: 7839

Javascript - If Statement Woes

I've been making use of AJAX in my website. AJAX is obviously a 2 way communication.

Here is PHP code which echoes an ID or the word ERROR:

$quickCheckQuery = mysql_query("SELECT * FROM pos WHERE type='$type' AND design='$design' AND medium_id='$medium'")or die("ERROR: ".mysql_error());
if(mysql_num_rows($quickCheckQuery)==0){
    mysql_query("INSERT pos VALUES(NULL, '$title', '$type', '$design', NULL, NULL, NULL, NULL, NULL, NULL, '$medium')")or die("ERROR: ".mysql_error());
    echo mysql_insert_id();
}else{
    echo "ERROR";   
}

And that does send the word ERROR or the inserted ID back to the client side, as expected.

Here is my "recieve response" in javascript:

if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
            var newId;
            newId = xmlhttp.responseText;

            if(newId=="ERROR"){
                alert(newId);
                alert("There is an ERROR");
            }else{
                alert(newId);
                alert("Processing Files");
            }

    }

Now, what this does is I receive 2 alerts per condition - One side of this could be:

Alert 1: ERROR
Alert 2: There is an ERROR

OR 

Alert 1: 5
Alert 2: Processing Files

However, What I am actually getting is:

Alert 1: ERROR
Alert 2: Processing Files

My if statement logic seems simple enough. I just can't kick this problem..

Upvotes: 1

Views: 176

Answers (3)

Harish
Harish

Reputation: 2324

because this might be doing the trick check that

die("ERROR: ".mysql_error());

Upvotes: 0

steve
steve

Reputation: 778

have you tried firebug or ie developer toolbar? You can then just set a breakpoint in your javascript (press f12 to open, then click on the script tab, find your receive script and click to set the breakpoint at the start of your if - then you can set watches etc), as this all looks correct - but as suggested, there are probably some non-alpha characters before / after error - this will be clear when you set a watch on it.

Otherwise, to debug without this, try alerting this: alert('"' + newId + '"'); to see if you have trailing spaces

Upvotes: 0

Jacob
Jacob

Reputation: 8334

Is there any additional whitespace in your php file. e.g. at the start or end.

Do you close your php file with ?>, if so don't.

You could try removing whitespace from the responseText.

newId = xmlhttp.responseText.replace(/(^\s+|\s+$)/g, '');

Upvotes: 2

Related Questions