skip to Main Content

I have a foreach loop on some items with an id, in which I have an ajax call. In success function, I want to attribute each response to its corresponding id. How can I do that? Because in succes my id is lost. How can I do something like that:

for (i=0; i<items_to_print.length; i++) {
  var item = items_to_print[i];

  jQuery.ajax({
    url: item.url,
    dataType: "json",
    data: item.data,
    success: function(response, i) {
      items_to_print[i]['response'] = response;
    }
  });
}

Thank you,

2

Answers


  1. One way to do it is to slow the loop down – only go to the next item in the array once you get a response.

    var items_to_print = [{url:"https...",data:{}},{url:"https...",data:{}},{url:"https...",data:{}}];
    
    var count = 0;
    makeCall();
    function makeCall(){
        if(count >= items_to_print.length){return;}
        var _item = items_to_print[count];
        jQuery.ajax({
        url: item.url,
        dataType: "json",
        data: item.data,
        success: _response
      });
    }
    
    function _response(response){
       items_to_print[count]['response'] = response;
       count++;
       makeCall();
    }
    
    Login or Signup to reply.
  2. Your problem here is that, when the success is called, i points to the last position of the array, so all responses are added to the last item (and only the last one that finishes perdures). This happens because the closure that success creates captures i, but the variable itself, not its current value when the function is defined, so all closures share the same reference to a variable — a variable that is being modified by the loop. To prevent this, you can use forEach instead of a for loop:

    items_to_print.forEach(function(item) {
        jQuery.ajax({
            url: item.url,
            dataType: "json",
            data: item.data,
            success: function(response, i) {
               item.response = response;
            }
        });
    });
    

    Doing it this way, for each item in the array you are calling a function, and so the item variable is different for each call, so success can capture it without a problem as it always points to the same object — the one for which the request was made.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search