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.

 

Related Articles

Fun @ WordCamp Pune

In my previous blog First WordCamp, I covered what we have done in WordCamp. Now in this blog, you will know what fun we did…

The last day ( છેલ્લો દિવસ )

Hi there, The last day, yes I am talking about the last day of the year 2016. Another year passed and I became 26 in…

First WordCamp

I am going to tell you about my first WordCamp which was held in Pune on 15th Jan 2017. And yes I was very happy…

Edit old commit message on github

Sometimes we make mistake in git commit message, especially spelling mistake. Even though I think twice before pressing the enter key after I write the…

WordCamp Mumbai

Whooaaaaaaaaa…!!!!!!!!!!!! Mumbaaaaaaaaiiiiiiiiiiiiiiiii…………………………………… Mayanagari…….. This was my 2nd WordCamp and it was at Mumbai. This WordCamp was like medicine for me as I had some problems…

Responses

Leave a Reply