Abort all running ajax on click jQuery

There may be times you want to stop ajax request on some event like on click, hover etc…

In my case, I wanted to run an ajax on click, but I wanted to cancel all other ajax request to be stopped before my ajax. So after lots of finding I found one solution here.

I used the last snippet because I didn’t get how I to use the above 2 snippets.

Below is the code worked for me:

$( document ).on( 'ready', function () {

	var xhrQueue = []; 

	$(document).ajaxSend(function(event,jqxhr,settings){
	    xhrQueue.push(jqxhr); //alert(settings.url);
	});

	$(document).ajaxComplete(function(event,jqxhr,settings){
	    var i;   
	    if((i=$.inArray(jqxhr,xhrQueue)) > -1){
	        xhrQueue.splice(i,1); //alert("C:"+settings.url);
	    }
	});

	window.ajaxAbort = function (){  //alert("abortStart");
	    var i=0;
	    while(xhrQueue.length){ 
	        xhrQueue[i++].abort(); //alert(i+":"+xhrQueue[i++]);
	    }
	};

})

Then I used ajaxAbort(); on my click event. And that’s it!!! All the previous ajax is stopped as shown in the video.

 

One thought on “Abort all running ajax on click jQuery”

Leave a Reply