1

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.

1
  • 1
    Read the section "Creating closures in loops: A common mistake" here Commented Apr 29, 2013 at 10:08

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);

});

Comments

0

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);
     }
});

Comments

-1

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.

5 Comments

async: false is bad practice and is going to be deprecated
Thanks for informing me, I'll edit my answer and put your feedback in it.
It's not just bad practice and deprecated. In some browsers it simply won't work.
Hmm, learn something new everyday. Do you want me to delete my post?
What browsers do not support async=false?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.