2

I have a jquery function which iterates through an array and calls servlet for each iteration. How can I make sure that the response from each servlet goes to respective div section. The div id is unique and corresponds to val in an array.

JQuery:

function foo() {

  for (var p in obj) {

    var tagId = obj[p]["prop1"];

    $.get('CallServlet', {
      json: JSON.stringify(obj[p])
    }, function(response) {
      $("#" + tagId).append(response);
    });

  }
}

Example:

tagId= obj[0][val1];

I want my response to go to :

<div id="tagId"></div>

In my function above the value of the tagId in the response is overwritten when the iterater advances through the objects. When I receive the response for obj[0], the tagId is updated to obj[1][val1]

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
user
  • 123
  • 2
  • 11
  • you do ajax inside the loop and when response return function take the last value of tagId, so you need to look at solution i provide to you using IIEF function – Abdelrahman M. Allam Jan 04 '16 at 22:10

2 Answers2

1

Because you're sending your ajax call in a loop, you can use the loop variable in the callback for your ajax call.

function(response){
    $("#"+tagId).append(response);
}

This will generate one different callback function for each iteration of the loop.

John Kossa
  • 459
  • 2
  • 8
  • I'm already using the loop variable "tagId". Since the iterater is incremented before the response, the tagID is updated to the next value before receiving the response. – user Jan 04 '16 at 21:55
  • 2
    I think he's saying that, (because "closure"), tagId is available in your function w/o passing it as a param. – John Hascall Jan 04 '16 at 22:01
1

You need to wrap it with the function with IIFE

function foo() {

  for (var p in obj) {

    var tagId = obj[p]["prop1"];
    (function(id) {
      $.get('CallServlet', {
        json: JSON.stringify(obj[p])
      }, function(response) {
        printFunc(responseText, id);
      });
    })(tagId)

  }
}