user user - 4 years ago 93
Javascript Question

How to pass additional parameter to Ajax response while sending request

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]

Answer Source

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)

  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download