title: jQuery Ajax, overwrite onreadystatechange handler
body: <p>I'm recently fooling around with some ajax polling techniques. However, it seems like I can't overwrite the <code>onreadystatechange</code> handler from a <code>XMLHttpRequest</code> object in FireFox (3.6.7).</p>
  
  <p>On tracking the problem why FF throws an exception when trying to access <code>onreadystatechange</code>, I realized it depends whether the <code>send()</code> method was called or not.</p>
  
  <p>In other words, here is an example (plain js, no jQuery so far), that works:</p>
  
  <p>(This is fairly simplified just for a demonstration)</p>
  
  <pre><code>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);
  </code></pre>
  
  <p>This works, better said it's possible to access <code>myxhr.onreadystatechange</code> 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.</p>
  
  <pre><code>myxhr.send(null);
  console.log("onreadystatechange function: ", myxhr.onreadystatechange);
  </code></pre>
  
  <p>Fails.</p>
  
  <p>So where is my actual problem?</p>
  
  <p>Well, I want to use jQuery's <code>$.ajax()</code>. But if I try to overwrite the <code>onreadystatechange</code> method of a <code>XHR</code> object that was returned from <code>$.ajax()</code>, I receive the same FireFox exception.</p>
  
  <p>Ok I already found out why this happens, so I thought about, hey what about the <code>beforeSend</code> property of <code>$.ajax()</code> ? So I basically tried this:</p>
  
  <pre><code>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);
     }
  });
  </code></pre>
  
  <p>Guess what, FireFox throws an exception. So what do you do now? You digg into the jQuery source, like I did. But that brought more questions than answers actually. It looks like <code>beforeSend()</code> is really called before <code>xhr.send()</code> is executed. So I'm wondering why on earth FireFox does not allow to overwrite the handler at this point.</p>
  
  <p>Conclusion?</p>
  
  <p>It's impossible to create a <code>custom readystatechange handler</code> with jQuery/Firefox ?</p>