0

Is it possible to send an ajax request, and intercept or see the HTML response code and then act upon it? I have a system that uses plain JS and XMLHttpRequest to see things like abort, error, and timeout, but it would be far more useful to track 404s and 409s etc.

This is my current code which is quite popular for this method

(function(open) {
            XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
                this.addEventListener("abort", function() {
                    self.trigger('abort');
                }, false);
                this.addEventListener("error", function() {
                    self.trigger('error');
                }, false);
                this.addEventListener("timeout", function() {
                    self.trigger('timeout');
                }, false);
                this.addEventListener("load", function() {
                    self.trigger('load');
                }, false);
                open.call(this, method, url, async, user, pass);
            };
        })(XMLHttpRequest.prototype.open);

But I am looking to switch on HTTP response codes. I also am tied into jQuery so I can use whatever jQuery setup options provide, but so far I haven't seen a way to get response codes.

Please note I am looking for a global solution. I cannot be adding 100s of individual function calls per individual ajax request.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • 1
    [this](http://stackoverflow.com/questions/5202296/add-a-hook-to-all-ajax-requests-on-a-page) should help – BenG Aug 20 '16 at 17:26
  • Why can't you get HTML response code? –  Aug 20 '16 at 17:29
  • Didnt realize it was easy to find in `this.status` – terry winkleheimer Aug 20 '16 at 17:38
  • As a note: you should not write `open.call(this, method, url, async, user, pass);` but `return open.apply(this, arguments)`. On the one hand you should always return the the result of the wrapped function, currently it does not return anything, but in future it might do, on the other hand you should use `apply` and `arguments` so that your wrapper does not depend on changes of the arguments. – t.niese Aug 20 '16 at 17:39

1 Answers1

0

Status property can easily be found in this

(function(open) {
   XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
   switch(this.status){
      // case 404: etc
   }
            open.call(this, method, url, async, user, pass);
        };
    })(XMLHttpRequest.prototype.open);