1

I want to immediately reject all AJAX requests depending on a variable. I understand how to hook the XMLHttpRequest but not sure how to reject it.

(function(open) {
            XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
                this.addEventListener("readystatechange", function() {
                    if(this.readyState === 1){
                        // stop all ajax attempts if we're disconnected
                        if(!self.isConnected){
                            console.log('rejecting')
                            // reject here
                            this.abort(); // ???
                        }
                    }
                }, false);
                open.call(this, method, url, async, user, pass);
            };
        })(XMLHttpRequest.prototype.open);

Also I want to know if calling this within this.readyState === 0 is akin to calling it "when the request first starts"

Tester232323
  • 301
  • 1
  • 11

2 Answers2

0

you can use abort function to abort the ajax request, first save your request in some variable and call abort on it

$(document).ready(
    var xhr;

    var fn = function(){
        if(xhr && xhr.readyState != 4){
            xhr.abort();
        }
        xhr = $.ajax({
            url: 'ajax/progress.ftl',
            success: function(data) {
                //do something
            }
        });
    };

    var interval = setInterval(fn, 500);
);

There is another approach of creating AJAX Pool setup, which I don't recommend, fiddle here

$.xhrPool = [];
$.xhrPool.abortAll = function() {
    $(this).each(function(idx, jqXHR) {
        jqXHR.abort();
    });
    $.xhrPool = [];
};

$.ajaxSetup({
    beforeSend: function(jqXHR) {
        $.xhrPool.push(jqXHR);
    },
    complete: function(jqXHR) {
        var index = $.xhrPool.indexOf(jqXHR);
        if (index > -1) {
            $.xhrPool.splice(index, 1);
        }
    }
});
Parag Bhayani
  • 3,280
  • 2
  • 28
  • 52
0

I simply added

this.abort()

and this seems to immediately abort all requests when desired.

Tester232323
  • 301
  • 1
  • 11