I have been tricked recently with some ajax polling methods. However, it seems I cannot overwrite the onreadystatechange handler from the XMLHttpRequest object in FireFox (3.6.7).
When tracking down the problem of why FF throws an exception when trying to access onreadystatechange , I realized that it depends on whether the send() method was called or not.
In other words, here is an example (plain js, without jQuery) that works:
(This is pretty simple to demonstrate)
var myxhr = new XMLHttpRequest(); myxhr.open("GET", "/my/index.php"); myxhr.onreadystatechange = function(){ console.log('ready state changed'); }; console.log("onreadystatechange function: ", myxhr.onreadystatechange); myxhr.send(null);
This works, itβs better to say that you can access myxhr.onreadystatechange here. If I switch the last two lines of code, FF throws an exception, basically saying that I am not allowed access to this object.
myxhr.send(null); console.log("onreadystatechange function: ", myxhr.onreadystatechange);
Fails.
So where is my actual problem?
Well, I want to use jQuery $.ajax() . But if I try to overwrite the onreadystatechange method of the onreadystatechange object that was returned from $.ajax() , I get the same FireFox exception.
Ok, I already figured out why this is happening, so I thought, what about the beforeSend $.ajax() property? So I basically tried this:
var myxhr = $.ajax({ url: "/my/index.php", type: "GET", dataType: "text", data: { foo: "1" }, beforeSend: function(xhr){ var readystatehook = xhr.onreadystatechange; xhr.onreadystatechange = function(){ readystatehook.apply(this, []); console.log('fired'); }; }, success: function(data){ console.log(data); }, error: function(xhr, textStatus, error){ console.log(xhr.statusText, textStatus, error); } });
Guess that FireFox throws an exception. So what are you doing right now? You digg into jQuery source like me. But in fact, it raised more questions than answers. It appears that beforeSend() actually called before xhr.send() executed. Therefore, I wonder why FireFox at this stage does not allow overwriting the handler.
Conclusion
Unable to create custom readystatechange handler using jQuery / Firefox?