Monitoring AJAX requests comes handy when we want to notify user about information loading, using default variables till AJAX requests finish or some other reasons. In this post I will show a small hack using which we can monitor all AJAX requests at a time. This will save time and make code more productive.
Simplest way of monitoring AJAX requets?
ajaxRequest1.open("GET", "ajax1.php", false);
ajaxRequest1.onload = function(){
console.log(ajaxRequest1.responseText);
}
ajaxRequest1.onprogress = function(){
console.log("loading");
}
ajaxRequest1.send(null);
var ajaxRequest2 = new XMLHttpRequest();
ajaxRequest2.open("GET", "ajax2.php", false);
ajaxRequest2.onload = function(){
console.log(ajaxRequest2.responseText);
}
ajaxRequest2.onprogress = function(){
console.log("loading");
}
ajaxRequest2.send(null);
In the above code we have the same implementation for onprogress event for our both AJAX objects. This takes more time and makes our code less productive because if we want to change the code than we have to change it in every onprogress event handler. And writing the same code again and again is wastage of time.
So I have made a small hack using which we can automate the implementation of onprogress event handler.
XMLHttpRequest.prototype.send = function(value) {
this.addEventListener("progress", function(){
console.log("Loading");
}, false);
this.realSend(value);
};
Here I am overriding the send method of XMLHttpRequest class and attaching progress event handler. And than calling the actual send method which is assigned to another property. Now all AJAX objects will have event handlers attached to them. This way we can monitor all AJAX requests on the web page.
So now we can write
XMLHttpRequest.prototype.send = function(value) {
this.addEventListener("progress", function(){
console.log("Loading");
}, false);
this.addEventListener("load", function(){
console.log(this.responseText);
}, false);
this.realSend(value);
};
var ajaxRequest1 = new XMLHttpRequest();
ajaxRequest1.open("GET", "ajax1.php", false);
ajaxRequest1.send(null);
var ajaxRequest2 = new XMLHttpRequest();
ajaxRequest2.open("GET", "ajax2.php", false);
ajaxRequest2.send(null);
Conclusion
In the similar way you can hack any javascript built in classes and attach some automation code. This simple idea can be used to do many more things in javascript.