jQuery multiple ajax call

As ajax is async, if you or your user triggers the event too fast, it may cause multiple ajax call. Also if You wont to loop ajax calls, the solution to the issue is to queue your ajax call.

JS - jQuery

// jQuery on an empty object, we are going to use this as our Queue
var ajaxQueue = $({});
var currAjaxCalls = [];

$.ajaxQueue = function(ajaxOpts) {
	
if(ajaxOpts == "dequeue") {
	if(currAjaxCalls.length > 0) {
		for(var i=0; i<currAjaxCalls.length; i++) {
			currAjaxCalls[i].abort();	
		}	
	}
	ajaxQueue.dequeue();

} else {	 
	// hold the original complete function
	var oldComplete = ajaxOpts.complete;
	
	// queue our ajax request
	ajaxQueue.queue(function(next) {
	
		// create a complete callback to fire the next event in the queue
		ajaxOpts.complete = function() {
		// fire the original complete if it was there
		if (oldComplete) {
			currAjaxCalls.slice(1);
			oldComplete.apply(this, arguments);
		}
		
		next(); // run the next query in the queue
		};
		
		// run the query
		currAjaxCalls[currAjaxCalls.length] = $.ajax(ajaxOpts);
	});
}

};

$.clearAjaxQueue = function() {
	$.ajaxQueue("dequeue");
};

Share the love

Leave a Comment

Please keep in mind that comments are moderated and rel="nofollow" is in use. You can use [code][/code] if you want to write codes. Don't spam us :) Thanks!

Advertisement