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: FireFox, JavaScript
October 29th, 2008 at 8:12 am
Thanks Man, it solved a big problem to me !!
November 29th, 2008 at 9:05 am
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!
December 12th, 2008 at 8:39 pm
THANKS! I was pulling my hair out.
February 3rd, 2009 at 5:54 pm
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
June 8th, 2009 at 10:00 am
Thank you man – your code really help. Save lot of time!
July 23rd, 2009 at 9:12 pm
You solved it and saved me a huge headache! Thank you!!!
June 25th, 2010 at 7:21 pm
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
December 11th, 2011 at 1:26 am
Thanks!