How do I queue jQuery ajax requests

September 21, 2011

I was recently doing some javascript testing and needed to make some asynchronous (sequential) ajax requests for authentication, creating of records, etc. As with all good things jQuery, the solution to this problem is to install the plugin. The ajaxq plugin, that is.

Installation is as simple as including it in your code.

[script language="javascript" src="/js/jquery-1.6.2.min.js"][/script]
[script language="javascript" src="/js/jquery.ajaxq.js"][/script]

Then calling the $.ajaxq method, which takes the queue name (use different names to run multiple asynchronous queues synchronously) and the settings object with the same parameters as jQuery’s ajax function.

$(function() {
	//Login, then logout
	$.ajaxq("queue", {
		url: '/api/user/login',
		type: "POST",
		data: { 
			username: "username", 
			password: "password"
		},
		success: function(data) {
			document.write("Logged in...
"); } }); $.ajaxq("queue", { url: '/api/user/logout', type: "POST", success: function(data) { document.write("Logged out...
"); } }); });

And finally, an example which runs two queues simultaneously:

$(function() {
	//Login, then logout
	$.ajaxq("one", {
		url: '/api/requestone',
		type: "POST",
		success: function(data) {
			document.write("Request one queue 'one'...
"); } }); $.ajaxq("two", { url: '/api/user/logout', type: "POST", success: function(data) { document.write("Request 1 queue 'two'...
"); } }); $.ajaxq("two", { url: '/api/user/logout', type: "POST", success: function(data) { document.write("Request 2 queue 'two'...
"); } }); });

Output could either be

Request 1 queue 'two'...
Request 2 queue 'two'...
Request 1 queue 'one'...

or

Request 1 queue 'one'...
Request 1 queue 'two'...
Request 2 queue 'two'...

Author

Stay in Touch!

Stay in Touch!
Solutions Architecture

browse through our blog articles

Blog Archive