Catch AJAX

During the last couple of days I've been fighting with AJAX. We use a weird-ass html generator due to historical reasons (I'm counting the days till we switch to something *cough*React*cough* better), and that generator sends its own, custom AJAX requests without a possibility to assign a callback to them or somehow let their success trigger anything. So, I've been searching the Internet for a solution, tried a few tips, and finally found a gem. So, here you are, courtesy of Dmitri Pavlutin and his blog. The only thing you need is this code snippet:

var open = window.XMLHttpRequest.prototype.open,
    send = window.XMLHttpRequest.prototype.send;

function openReplacement(method, url, async, user, password) {
  this._url = url;
  return open.apply(this, arguments);
}

function sendReplacement(data) {
  if(this.onreadystatechange) {
    this._onreadystatechange = this.onreadystatechange;
  }
  /**
   * PLACE HERE YOUR CODE WHEN REQUEST IS SENT  
   */
  this.onreadystatechange = onReadyStateChangeReplacement;
  return send.apply(this, arguments);
}

function onReadyStateChangeReplacement() {
  var original_response, modified_response;
  /**
   * PLACE HERE YOUR CODE FOR READYSTATECHANGE
   * There will be three states, 2, 3, and 4 — with 4 meaning "complete"
   */
  if(this._onreadystatechange) {
    return this._onreadystatechange.apply(this, arguments);
  }
}

window.XMLHttpRequest.prototype.open = openReplacement;
window.XMLHttpRequest.prototype.send = sendReplacement;

Essentially what that does is it replaces the default ajax request sender and opener with custom ones which do something you need to do and then call the respective default handlers.

Share
Pin
Like
Send
Share
Send
Send
Share
Anton Zujev
Ostrava, Czechia