Back jQuery

jQuery multiple ajax call

WRITTEN BY ON 10 Oct 2011
20,686 VIEWS • SHARES
1 comment

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");
};
Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

1 comment
Lucian Vasile 12 years ago
Awesome code snippet is awesome
Reply