Ajax function into a loop

I request your answer for a issue I've got (part is an array):

for(i=1;i<part.length;i++){
    $("#content").append('<div id="id' + i + '"></div>');
    $.get('ajax.php?id=' + i, function(data) {
        console.log("cache" + i);
        $("#id" + i).html(data);
    });
});

The problem is that into $.get function, the i value is the value of I when the loop is ended. As there are 140 row in my Array (part), I will always be 140, not 1 then 2 then 3 ..

How to get the i value in the ajax callback ?

Thanks for reply.

Upvotes: 1

Views: 106

Answers (4)

Alnitak
Alnitak

Reputation: 339786

Note that your loop will try to fire off as many AJAX requests at a time as your browser will permit, with no guarantee that they'll complete in any particular order.

If you really must fire off 140 AJAX requests, I suggest this, instead:

var i = 1;
(function loop() {
    if (i < part.length) {
        $("#content").append('<div id="id' + i + '"></div>');
        $.get('ajax.php?id=' + i).done(function(data) {
            console.log("cache" + i);
            $("#id" + i).html(data);
            i++;
        }, loop);
     }
});

Upvotes: 0

skuntsel
skuntsel

Reputation: 11742

Or alternatively, get a JSON from server and iterate over it:

$.get('ajax.php', { from: 1, to: 140 } ).done(function(data) {
    $(data).each(function(index) {
        //do something with this and index
    });
});

This way you'll have access to index internally and will fire only one request to server, thus not polluting the network.

Upvotes: 2

MMeersseman
MMeersseman

Reputation: 2631

Guffa his answer should work, you could also use the $.ajax-version and put async-parameter to false. Check out the documentation to see how to use it.

Edit: It should be noted though that using async: false is a bad practice and will be deprecated.

Upvotes: -1

Guffa
Guffa

Reputation: 700212

As the AJAX call is asynchronous, all the callbacks run after the loop.

You can use a function expression to create a separate variable for each iteration:

for(i=1;i<part.length;i++){
  $("#content").append('<div id="id' + i + '"></div>');

  (function(i){

    $.get('ajax.php?id=' + i, function(data) {
      console.log("cache" + i);
      $("#id" + i).html(data);
    });

  })(i);

});

Upvotes: 0

Related Questions