jQuery Ajax, overwrite onreadystatechange handler

jQuery Ajax, overwrite onreadystatechange handler

Hi Folks,

I'm recently fooling around with some ajax polling techniques. However, it seems like I can't overwrite the onreadystatechange handler from a ` XMLHttpRequest` object in FireFox (3.6.7).

On tracking the problem why FF throws an exception when trying to access ` onreadystatechange`, I realized it depends whether the ` send()` method was called or not.

In other words, here is an example (plain js, no jQuery so far), that works:

(This is fairly simplified just for a demonstration)

  1.     var myxhr = new XMLHttpRequest();
  2.     myxhr.open("GET", "/my/index.php");
  3.     myxhr.onreadystatechange = function(){
  4.         console.log('ready state changed');
  5.     };
  6.     console.log("onreadystatechange function: ", myxhr.onreadystatechange);
  7.     myxhr.send(null);

This works, better said it's possible to access ` myxhr.onreadystatechange` here. If I switch the last two lines of code, FF throws an exception, basically telling me that I'm not allowed to access this object.

  1.     myxhr.send(null);
  2.     console.log("onreadystatechange function: ", myxhr.onreadystatechange);

Fails.

So where is my actual problem?

Well, I want to use jQuery's ` $.ajax()`. But if I try to overwrite the ` onreadystatechange` method of a ` XHR` object that was returned from ` $.ajax()`, I receive the same FireFox exception.

Ok I already found out why this happens, so I thought about, hey what about the ` beforeSend` property of ` $.ajax()` ? So I basically tried this:

  1.     var myxhr = $.ajax({
  2.        url:        "/my/index.php",
  3.        type:       "GET",
  4.        dataType:   "text",
  5.        data:        {
  6.            foo:    "1"
  7.        },
  8.        beforeSend: function(xhr){
  9.            var readystatehook = xhr.onreadystatechange;

  10.            xhr.onreadystatechange = function(){
  11.                readystatehook.apply(this, []);
  12.                console.log('fired');
  13.            };
  14.        },
  15.        success:    function(data){
  16.            console.log(data);
  17.        },
  18.        error:      function(xhr, textStatus, error){
  19.            console.log(xhr.statusText, textStatus, error);
  20.        }
  21.     });

Guess what, FireFox throws an exception. So what do you do now? You dig into the jQuery source. But that brought more questions than answers actually. It looks like ` beforeSend()` is really called before ` xhr.send()` is executed. So I'm wondering why on earth FireFox does not allow to overwrite the handler at this point.

Conclusion?

It's impossible to create a ` custom readystatechange handler` with jQuery/Firefox ?