Just the weekly tutorials.

How to queue (more than one) Ajax calls using jQuery without overwhelming your browser with HTTP requests

Once upon a time I wanted to call several HTTP requests in a row. My first idea was to put them into a for-loop. I figured the asynchronous nature of ajax would sort everything out.

var queue = ["a.php", "b.php", "c.php", "d.php", "e.php", "f.php", "g.php"]; for (var i = 0; i < 7; i++) $.ajax( { url: queue[i], success: function() { /* it is finished */ } });

The scripts were doing some major processing and took a while. I was trying to read database data and call a complex MySQL query in each one. It took a few seconds to execute just one script.

The for-loop called all 7 ajax methods at once. They actually got queued in the browser. And regardless of when the next script has finished executing, they sort of all began to execute at once.

The browser came to a halt for over a minute.

The browser queued up so many asynchronous requests that they were not able to execute at the same time. Thus, they were no longer asynchronous.

It's true, executing several ajax calls that work with a script that does some heavy processing can put a strain on the program, possibly preventing it from normal function. In this tutorial we will discover a few ways jQuery's ajax method can be used to prevent this from happening and learn a few things about JavaScript at the same time.

jQuery Ajax: A Brief Overview

Let's say you have my jquery tutorial book (which talks about jQuery ajax events) and you have further learned how to make Ajax calls using the jQuery's method $.ajax(); The techniques shown in this tutorial are not discussed in my tutorial book. It deals with executing a number of ajax calls in a row without overwhelming the browser.

Perhaps you have read How to make an Ajax call using jQuery tutorial. Whatever the case, I assume you understand how to make basic Ajax calls at this time.

By now you have constructed several web pages and learned how to dynamically load content into them. If not, let's briefly take a look at how Ajax works in jQuery:

Using the $.ajax(); method together with $("#target").html(ajax_return_value); we can insert the content of the script into the HTML element #target:

$.ajax( { url : 'my-script.php', type : 'POST', data : { var1: 15, var2: "Hello string." }, success : function(msg) { /* Insert script results into an HTML element */ $("#target").html( msg ); } });

The success property here refers to an anonymous function (anonymous aka nameless functions are described in this article). The entire ajax call is treated as an event, and the nameless function in this context is referred to as the event's callback function. It simply returns the result from the script that was called.

This code submits a POST HTTP request with two variables var1 and var2. Optionally, we displayed the results returned from my-script.php inside DIV#target HTML element. Perhaps this has become a habit and you freely create Ajax requests in your web projects.

Calling More Than One Ajax Function In a Row

But you've been around, and now you are looking to start using Ajax more extensively as your experience grows. Such things are needed in a web project that requires loading two pages at once. Or loading user settings to match their values with content which is loaded through Ajax, too.

You can probably do all of what was just described using consequent $.ajax() calls, as shown in the following example:

$.ajax( { url: "my-script-1.php", success: function(msg) { /* results */ } } ); $.ajax( { url: "my-script-2.php", success: function(msg) { /* results */ } } );

Notice that the type parameter is omitted. By default, Ajax requests are sent using the GET HTTP method. The custom msg parameter is used for intercepting (receiving) the result returned from the script which is simply its result as an HTML web page. You could make an ajax call to a page with extension *.html as well or your *.asp script or any other.

Sure, we can do this. It will work because the A in Ajax stands for Asynchronous. Both of the scripts here my-script-1.php and my-script-2.php will be called at approximately the same time.

Creating an Ajax Callback Chain

If our script file takes long to process (for example: doing a difficult calculation, collecting data from a complex MySQL query, editing an image using the PHP image library, or otherwise doing something that takes several seconds) you will quickly notice that these requests may intervene with the smooth performance of your web application.

When it comes to making Ajax calls in a sequence, small scripts will do okay. You may get away with 5-20 ajax calls in a row, or even more. At one point your application will begin to slow down, interrupting common actions such as using the browser's scroll bar. It may look like your website came to a halt (as much as these HTTP requests are asynchronous, a large number of them fired at the same time does not prevent your browser from overload/overwhelm.)

There are times when you need to perform an operation over and over again without losing performance. In this case an Ajax queue must be created. When the number of ajax calls is known ahead of time we can simply create an ajax-callback chain.

<!-- An example of Ajax chain //--> $.ajax( { url: "script-1.php", success: function(msg) { $.ajax( { url: "script-2.php", success: function(msg) { $.ajax( { url: "script-3.php", success: function(msg) { } } ); } } ); } } );

Simply call your second, third or fourth ajax call once the previous one returns success. Each success function is the event's callback function. Learn more about callback functions here.

Creating an Ajax Queue when the Number of Calls is Unknown

But what if the number of ajax events is unknown until the script execution time? What if it is based on an arbitrary number? We can no longer rely on the solution outlined above, one of creating a callback chain of ajax events. Therefore it must be created properly. This means designing it ourselves as a custom Ajax queue processor.

It's not that we will no longer use nameless callback functions. But that we will create them dynamically using our JavaScript program. This will take writing some custom JavaScript code. You know, with JavaScript variables and the like. The following script accomplishes that. It holds several JavaScript lessons that will be discussed afterwards.

We have to assume that the script files will come from some place, such as a database or a text file. Whatever the source is, the queue assumes that we know beforehand which files will be executed. In this example they will be stored using a JavaScript array.

var queue = ["a.php", "b.php", "c.php", "d.php", "e.php", "f.php", "g.php"]; var execute_queue = function(index) { $.ajax( { url: queue[index], success: function( { index++; // going to next queue entry // check if it exists if (queue[index] != undefined) { execute_queue(index); } } }); // end of $.ajax( {... }; // end of execute_queue() {... var index = 0; execute_queue(index); // go!

This code will create an ajax queue. It means that until the current script is not finished executing, the next script will not be called. There is no need to make multiple ajax calls.

If there was a single line of code here that defines the key principle to how the entire queue works, it is probably the following:

$.ajax( { url: queue[index], // ...code continues...

Here, instead of providing jQuery's ajax method with a URL as string value, we get a value at the current index in the queue array. This index will increment each time the function calls itself. And that happens if the $.ajax() call was successful.

The function execute_queue will call itself the number of times equal to the number of entries in the queue array. This continues until all entries in the queue are depleted.

Dynamic Nature of the Queue

The queue can be constructed dynamically. In this case an array is used. These values can come from a database or another script.

There is only one function at work here: execute_queue. It is called only once to trigger the queue. After that, it will continue calling itself again from within its own body.

When a function calls itself from its own body, it is referred to as a recursive function in JavaScript (and other programming languages.) The $.ajax() method is called several times until there is nothing left in the queue array.

This technique will prevent the browser from being overwhelmed with HTTP requests. It accomplishes this by calling a number of scripts in a sequence one after another, instead of all at once.

Just the weekly tutorials.