Skip to content Skip to sidebar Skip to footer

Can One Replace Xhr.onreadystatechange With Xhr.onload For Ajax Calls?

I need to support major modern browsers only (IE10+, FF, Chrome, Safari) Can I make this substitution as I want to simplify my code base: From: xhr.onreadystatechange = function ()

Solution 1:

maybe you take a look at this one and a look at W3C: XMLHttpRequest it's the same if your browser supports xhr.onload. Requires XMLHttpRequest 2)

You can also write a wrapping function that emulates xhr.onload if it's not present. (I think you need to override XMLHttpRequest.prototype.onload = function(args){//calling onreadystatechanges somehow}). If you only support modern browsers using xhr.onload should be available - the best solution is using a framework (like or that provides wrapping functionality for that.

Solution 2:

In the MDN documentation they state the following

Events

onreadystatechange as a property on the xhr object is supported in all browsers.

Since then, a number of additional event handlers were implemented in various browsers (onload, onerror, onprogress, etc.). These are supported in Firefox. In particular, see nsIXMLHttpRequestEventTarget and Using XMLHttpRequest.

More recent browsers, including Firefox, also support listening to the XMLHttpRequest events via standard addEventListener APIs in addition to setting on* properties to a handler function.

So I think you can assume that onreadystatechange is the way to go and onload is a addition that can be used if the browser supports it. @mr.VVoo answer is the correct one, to stick to w3c when in doubt.

Solution 3:

Since the original asker said "I need to support major modern browsers only (IE10+, FF, Chrome, Safari)" it is obvious that onload, onerror, etc are the ways to go. Also, as of today, onreadystatechange is pretty much obsolete, as you are obviously not going to support anything that old that it supports onreadystatechange only.

To sum it up, forget about onreadystatechange.

Solution 4:

You can clean up your first example by doing this

xhr.onreadystatechange = function () {
    if (this.readyState === 4 && this.status === 200) {
        o.callback(xhr.responseText);
    } else {
        returnfalse;
    }
};

Note, you probably want to check onload too with this.status === 200 if you are doing something with the else statement. Although, if you are checking for errors, there is also onerror, which you can write something like

xhr.onerror = function(){
    console.log('Error: Do something else...');
}

Post a Comment for "Can One Replace Xhr.onreadystatechange With Xhr.onload For Ajax Calls?"