1

How can I make each iteration a new Ajaxcall that needs to be async. without using

async: false,

If I do this with the async I get a warning message, and my UI Freezes, how can I fix this? This is not a normal for loop

EDIT1

var username = "username1";
var password = "test";
var code = "";
for(var i = 0; i < results.lenght;i++){

   $.ajax({
        data: {username:username, password: password},
        url: './php/'+results[i].NAME+'.php',
        method: 'POST',
        datatype: 'json',
        success: function(msg) {
           //all the msg info needs to be filled in in the html. via the var "code"
        }
        });    
    }
return code;
vanlooverenkoen
  • 2,121
  • 26
  • 50

2 Answers2

2

Use the promise semantics of jQuery Ajax requests.

var params = {
    username: "username1",
    password: "test"
};

// build an array of Ajax requests
var requests = results.map(function (result) {
    var url = './php/' + encodeURIComponent(result.NAME) + '.php';
    return $.post(url, params, null, 'json');
});

// wait until all requests are done with $.when()
$.when.apply($, requests).done(function (responses) {
    responses.forEach(function (data) {
        // fill the data into the html
    });
});

See http://api.jquery.com/jquery.when/ and related pages, especially http://api.jquery.com/category/deferred-object/.

Tomalak
  • 332,285
  • 67
  • 532
  • 628
1

You can do something along these lines (haven't tested the code):

function doIteration(done, i){
    if(i <= 0){ done(); return; }

    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function(){
        if(xmlHttp.readyState == 4)
        {
            if(xmlHttp.status == 200){
                // Process response...
                console.log(xmlHttp.responseText);

                // Do next iteration.
                doIteration(done, --i);
            } else {
                doIteration(done, 0);
            }
        }
    };
    xmlHttp.open("method", "script.php");
    xmlHttp.send(null);
}

doIteration(function(){
    alert("Done loop!");
}, 10);

EDIT: Didn't realize you were using jQuery, just replace the xmlHttp requests with $.ajax and leave async enabled.

noahnu
  • 3,479
  • 2
  • 18
  • 40