Skip to content Skip to sidebar Skip to footer

Jquery Ajax, Overwrite Onreadystatechange Handler

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.

Solution 1:

I agree with Maz here, you can still benefit form the query handling and creating of the object, and also no need to patch jquery for this

however, if you dont mind patching jquery you could add these lines

// The readystate 2
        } elseif ( !requestDone && xhr && xhr.readyState === 2 && isTimeout !== 'timeout' && s.state2) {
            s.state2.call( s.context, data, status, xhr );
        // The readystate 3
        } elseif ( !requestDone && xhr && xhr.readyState === 3 && isTimeout !== 'timeout' && s.state3) {
            s.state3.call( s.context, data, status, xhr );

before this line: (jQuery v 1.4.4) or just search for the readyState === 4 in the source

// The transfer is complete and the data is available, or the request timed out
        } elseif ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {

now you can use the $.ajax again and put a handler up for state2 and state3 like so:

$.ajax({
    url: 'http://www.stackoverflow.com',
    cache: false,
    success:function(){console.log('success');},
    error: function (){console.log('error');},
    complete: function (){console.log('complete');},
    state2: function (context,data,status,xhr) {console.log('state2');},
    state3: function (context,data,status,xhr) {console.log('state3');}
});

it doesnt exactly behave like the other handlers, eg returngin false wont do a thing but you can still handle the xhr object and abort that way

ill see if i can submit this to be included in the source later this day, who knows they might accept it

Solution 2:

If you want a large level of customization, you can just get the XMLHttpRequest object and control it yourself.

var x=new $.ajaxSettings.xhr();
x.onreadystatechange=function(){ ... }
...

Solution 3:

You can do this by doing something like that:

$.ajax({
type: "POST",
url: "Test.ashx",
data: { "command": "test" },
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "json",
beforeSend: function (request, settings) {
    $(request).bind("readystatechange", function (e) { alert("changed " + e.target.readyState); });
}});

Post a Comment for "Jquery Ajax, Overwrite Onreadystatechange Handler"