Dheeraj Kumar Aggarwal
Dheeraj Kumar Aggarwal

Reputation: 642

Hook into XMLHttpRequest open and send method

I am using the following code to hook into XMLHttpRequest open/send methods:

var lastParams = '';
var send = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(data){
   lastParams = data;
   send.call(this, data);
};

var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, uri, async, user, pass) {
    this.addEventListener("readystatechange", function(event) {  
    if(this.readyState == 4){
       var self = this;
       var response = {
         method: method,
         uri: uri,
         params: lastParams,
         responseText: self.responseText
      };
      console.log(response);  
    }
  }, false);
  open.call(this, method, uri, async, user, pass);
};

It is working fine in the case of single ajax request at a time.

When multiple ajax request are firing at a time, then lastParams can contain wrong data (means lastParams can contain data from other ajax request). I want to uniquely associate the lastParams with request's other attributes?

Is there any id attribute in XMLHttpRequest so that I can uniquely identify the ajax request instance?

Thanks in advance.

Upvotes: 3

Views: 4628

Answers (3)

jpillora
jpillora

Reputation: 5262

Have a look at https://github.com/jpillora/xhook and the demos

//modify 'responseText' of 'example2.txt'
xhook.after(function(request, response) {
  if(request.url.match(/example\.txt$/)) {
    response.text = response.text.replace(/[aeiou]/g,'z');
  }
});

Upvotes: 2

brianff
brianff

Reputation: 175

why not make 'lastParams' as an array, and you always push data, instead of overwriting it everytime.

Upvotes: 0

Andrew D.
Andrew D.

Reputation: 8230

For uniquely associating some data with specified XMLHttpRequest instance you can simply add property into XMLHttpRequest instance and save data into property. For example:

// generating data for request
var data=generateData();

// sending data
var xhr=new XMLHttpRequest();
xhr.open("POST","/yourpage.php",true);
xhr.onreadystatechange=function(event){
  if(this.readyState===4){
    console.log(this.mySendedData);
  }
};
/** if you need to preserve 'data' variable value for each xhr **/
xhr.mySendedData=data;
/***************************************************************/
xhr.send(data);

Upvotes: 1

Related Questions