views:

2443

answers:

3

How could the following code sometimes evaluate to false?

(transport.responseText == '1' || transport.responseText == 'CARD_VALID')

My code is as follows:

if (transport.responseText == '1' || transport.responseText == 'CARD_VALID') {
 // do something....
}
else if (transport.responseText == 'CARD_INVALID' || transport.responseText == 'INVALID_CHECKSUM') {
 // do something else....
}
else {
 new Ajax.Request('/report_error.php?responseText='+transport.responseText);

 // report error to user
}

This is in the middle of an Ajax call and generally works, but sometimes (about once a day) it turns out that users will have what appears to be a response "CARD_VALID" in our logs, but will claim they received an error. I have started logging the response they received and the log files (made by the page report_error.php) that they are receiving "CARD_VALID"!

So, basically, it sounds like ('CARD_VALID' == 'CARD_VALID') is evaluating to false for certain users.

I have been logging the user agent and in the most recent case it was "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; (R1 1.5); .NET CLR 1.0.3705; .NET CLR 2.0.50727; MSN OptimizedIE8;ENUS)".

If anybody has had a similar experience or some advice on how to fix this, I would appreciate the help. Thanks.

+2  A: 

Try capturing the value of responseText into a different variable before entering that code block, in case the variable is updated somewhere in there.

I don't have that much experience directly using XmlHttpRequest, but I do know that javascript has a number of places where it uses volatile references to interface objects that can change during execution, rather than a simple value.

Joel Coehoorn
Good idea but is that possible? I thought JS was mono-threaded.
PhiLho
Thank you for the answer. That made sense to me, so I tried it. However, we are still getting in the error log "CARD_VALID" implying that JS evaluated ('CARD_VALID' == 'CARD_VALID') to false. Any other thoughts? This is one or two per day out of hundreds of successful. The only "pattern" is that the for most of them the user-agent appears to be IE7 or IE7, however there was one that was IE6...
jeffp
Correction: "IE7 or IE8"
jeffp
+1  A: 

I had a similar problem where two obviously identical strings would not be equal, and I was pulling my hair out trying to solve it, so I did this:

for (var c=0; c<string_1.length; c++) {
    if (string_1.charCodeAt(c) != string_2.charCodeAt(c)) {
     alert('c:'+c+' '+string_1.charCodeAt(c)+'!='+string_2.charCodeAt(c));
     valid = false;
    }
}

And I found that the last character on one string was 10, and the last character on the other was 13, I thought both strings were null terminated, but they were not.

Robert
A: 

try using === to match exactly(type and value)(recommended comparison operator in javascript). though that should not be a problem in this case I suppose.

sat