jordankaiser
1/23/2019 - 9:54 PM

Call a function on all ajax requests

var origOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
    console.log('request started!');
    this.addEventListener('load', function() {
        console.log('request completed!');
        console.log(this.readyState); //will always be 4 (ajax is completed successfully)
        console.log(this.responseText); //whatever the response was
    });
    origOpen.apply(this, arguments);
};

Call a function on all ajax requests

Taken from Stack Overflow.

Something you may want to adjust is the 'open' on 'XMLHttpRequest.prototype.send'. I say this as another example I saw goes like this.

  const origOpen = XMLHttpRequest.prototype.send;
  XMLHttpRequest.prototype.send = function () {
    this.addEventListener('load', () => {
      // Do things
    });
    origOpen.apply(this, arguments);
  };

I do not understand the origOpen.apply(this, arguments); part.

The all ajax requests means all which can trip you up. If you want to respond to a specific ajax event then you can do something like this:

XMLHttpRequest.prototype.send = function () {
  this.addEventListener('load', () => {
    // Only listen to vendor concessions ajax responses.
    if (this.responseURL.indexOf('vendor-concessions') !== -1) {
      VendorFormAnimation();
    }
  });
  origOpen.apply(this, arguments);
};