Zak
Zak

Reputation: 2698

Is it possible to have a semi-async ajax call in jQuery?

I'm working on a site that involves looping through an array, using a jQuery ajax call for each element. Here is a simplified version:

var myArray=new Array("El1","El2","El3","El4");
for(var i=0; i<myArray.length; i++){
     $.ajax({
         url: 'page.php?param='+myArray[i],
         success: function(data){
               //doing stuff with the data
               //this needs to complete before the loop advances
         }
     });
 }

I need each call to complete before advancing through the loop. I tried setting async:false, which makes the loop work correctly, but that holds up the rest of the page's scripts and causes a lot of lagging. Is there some way that I can prevent the loop from advancing until the call is complete, but still be able to run other scripts asynchronously?

Upvotes: 3

Views: 189

Answers (3)

GolezTrol
GolezTrol

Reputation: 116110

Call the next request in the success-handler of the previous. Something like this. (Could be a more elegant construct for this).

var myArray=new Array("El1","El2","El3","El4");
var i = 0;

function callAjax()
{
    $.ajax({
        url: 'page.php?param='+myArray[i],
        success: function(data){
            //doing stuff with the data
            //this needs to complete before the loop advances       

            if (i < myArray.length)
            {
                i++;
                callAjax();
            }
        }
    });
}

Upvotes: 1

karim79
karim79

Reputation: 342635

There's no need for a loop if you make use of Array.shift:

var myArray = new Array("El1", "El2", "El3", "El4");

function doRequest() {
    if (!myArray.length) return;
    var current = myArray.shift();
    $.ajax({
        url: 'page.php?param=' + current,
        success: function(data) {
            //doing stuff with the data
            doRequest();
        }
    });
}

Upvotes: 3

Jacob
Jacob

Reputation: 78840

var idx = 0;
var urls = ["El1","El2","El3","El4"];

var doNextRequest = function() {
    $.ajax({
        url: 'page.php?param=' + urls[idx],
        success: function(data) {
            // ...
            idx++;
            if (idx < urls.length) {
                doNextRequest();
            }
        }
    });
}

doNextRequest();

Upvotes: 6

Related Questions