12

I'm working on a project that has several scripts that I cannot change. These scripts update the page via AJAX. When the update is complete I need to run some code.

Is there any event that fires when any XMLHttpRequest is complete? (or any XMLHttpRequest state change?).

Unfortunately I cannot access the specific XMLHttpRequest object used to make the request.

Thanks,

MCM
  • 469
  • 1
  • 6
  • 17
  • 4
    If you're using jQuery exclusively for said ajax, yes. ajaxComplete. – Kevin B Aug 15 '13 at 18:34
  • @KevinB's suggestion would only work if the scripts that are not under your control rely on jQuery ajax. – Christophe Aug 15 '13 at 18:36
  • @Christophe That's what KevinB's comment says - `If you're using jQuery exclusively for **said ajax**,` – Ian Aug 15 '13 at 18:37
  • @Ian my point is that it's not just about what the OP is using, but also about what was used in the other scripts he didn't write. I doubt the other scripts rely on jQuery because the OP explicitly mentions the XMLHttpRequest object. – Christophe Aug 15 '13 at 18:41
  • 1
    Do i really have to be that exact? i thought my comment covered both cases pretty well. said ajax, being ajax requests he wishes to know when they are done. – Kevin B Aug 15 '13 at 18:42
  • @Christophe The OP mentioned the AJAX that the uncontrolled scripts are using. And that's exactly what KevinB was referring to (as well as any other AJAX they may be using, but the OP didn't even mention that) – Ian Aug 15 '13 at 18:44
  • @KevinB, I tried that earlier, unfortunately the scripts that are making the request are using .Net UpdatePanels (or something like that...), not jQuery. Thanks though. – MCM Aug 16 '13 at 00:15

1 Answers1

18

Without jQuery, you can hook the open method to attach a listener for each XHR object's readystatechange events at the time the XHR object is opened. Ensure the following code runs before any Ajax occurs:

// save the real open
var oldOpen = XMLHttpRequest.prototype.open;

function onStateChange(event) {
    // fires on every readystatechange ever
    // use `this` to determine which XHR object fired the change event
}

XMLHttpRequest.prototype.open = function() {
    // when an XHR object is opened, add a listener for its readystatechange events
    this.addEventListener("readystatechange", onStateChange)

    // run the real `open`
    oldOpen.apply(this, arguments);
}

Alternatively, if you only care about successful load events, you can listener for that event instead of readystatechange.

apsillers
  • 112,806
  • 17
  • 235
  • 239
  • Kindof works, but not really in my case : The requests are triggered multiple times and sometimes completely looped. – Jurion Jun 21 '18 at 15:36