FireFox bug with onreadystatechange

Just ran into this bug in FireFox: https://bugzilla.mozilla.org/show_bug.cgi?id=412112. Basically, if you do a synchronous call on an XMLHttpRequest object, the onreadystatechange function is not called. So the following code doesn’t work.

var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4)
  if (request.status == 200) alert('request successful')
};
request.open("GET", "/index.html", false); /* the false here makes it synchronous *
request.send(null);


Instead you must assume that the synchronous send has completed and instead check the status and process the response immediately. <edit> This means you do not need to define an onReadyStateChange function at all </edit> So:

var request = new XMLHttpRequest();
request.open("GET", "/index.html", false); /* the false here makes it synchronous */
request.send(null);
if (request.status == 200) { /* the request has been returned */
  alert("request successful")
}

This can actually be easier to code, but to me it was unexpected. I would expect that the
onreadystatechange be called when the response comes back either way. And if the synchronisity of the call is variable, it could get more interesting.

Tags: ,

8 Responses to “FireFox bug with onreadystatechange”

  1. Satrapo Says:

    Thanks Man, it solved a big problem to me !!

  2. Gorodn Says:

    Thanks, I was struggling with this in firefox, but it was fine in IE and Safari. Now with the dropping of the onreadystatechange (for synchronous) it works great…whew!

    keep up the good work!

  3. BV Says:

    THANKS! I was pulling my hair out.

  4. David Ness Says:

    Thanks! That did the trick. Once I realized that you were saying that I shouldn’t even make the call to onreadystatechange, because for a synchonous request there is no need to test for readyState == 4, and that I should just proceed with what I need to do, everything works as it should in all browsers. Thank you again very much. – David

  5. Axilees Says:

    Thank you man – your code really help. Save lot of time!

  6. Mike Says:

    You solved it and saved me a huge headache! Thank you!!!

  7. José Rodrigo Rodriguez R. Says:

    Thank you very much “One John” has taken me several hours to get Firefox to work properly synchronous Ajax method. I found your blog and I have opened my eyes, I posted on my Twitter (@ hantitesis) your entry, thanks again.

    Greetings from Cordoba, Veracruz, Mexico

  8. ^ Says:

    Thanks!

Leave a Reply