Tag Archives: when

Simultaneous AJAX requests with jQuery’s $.When

Let’s say you need to request different services, but only continue your flow (show a dialog, enable some UI element, navigate, etc) when all those calls are complete. That is something you may achieve in several ways, like a timer, a flag check, etc. but jQuery provides a really powerful method called $.when that is based on Deferred object that receives N amount of $.ajax requests and chained either with $.done, $.fail, or $.then you can act based on all responses of your services. It really worth the reading on jQuery documentation ;) and here is a quick example.

The below code performs 3 “simultaneous” requests to Twitter Search API and by chaining with $.then we’ll receive on the callback the result of the 3 requests. Note that this is by far the best implementation and it is only this way to easy the example and focus on $.when functionality.

 

function getAjaxRequest(query) {
	return $.ajax({
		url: 'http://search.twitter.com/search.json',
		dataType: 'jsonp',
		data: {
			q: query,
			result_type: 'recent'
		}
	});
}

$(function() {
	$.when(getAjaxRequest('jquery'), getAjaxRequest('javascript'), getAjaxRequest('backbonejs')).then(function(jquery, javascript, backbonejs) {

		$.each(jquery[0].results, function(key, item){
			$('#jquery').append('<li><strong>' + item.from_user + '</strong>: ' + item.text + '</li>');
		});

		$.each(javascript[0].results, function(key, item){
			$('#javascript').append('<li><strong>' + item.from_user + '</strong>: ' + item.text + '</li>');
		});

		$.each(backbonejs[0].results, function(key, item){
			$('#backbonejs').append('<li><strong>' + item.from_user + '</strong>: ' + item.text + '</li>');
		});
	});
});

 

You can also watch it here or look at the code here.