I want to call ajax in a loop, while my URL is also changed in each iteration.
problem: I get the same last respond, from both 2 iterations.
I tried to use closure, as suggested in Javascript loop with ajax call
but the responds are still the same.
maybe the problem comes because I use request.responseText
instead of jsonData
so –
-
How can I use
jsonData
?or
-
How can I get different
request.responseText
in each iteration ?
sample code:
function getLimitedSysInfo() {
var $myObjects = $('.some-class');
$myObjects.each(function() {
var objId = $(this).attr('id');
var eId = objId.substring("my_obj".length);
(function(eId) { // use closure: https://stackoverflow.com/questions/43191608/javascript-loop-with-ajax-call
var strURLGet = "http://www.test.com/my_test/get_info.php?p1=p1val&e=" + eId;
console.log(eId + " -> " + strURLGet); // => prints out as expected
request = $.ajax({
type: "get",
url: strURLGet,
cache: false,
complete: function(jsonData) {
console.log("fSys() complete"); // => prints out as expected
},
success: function(jsonData) {
console.log("fSys() success"); // => prints out as expected
console.log("fSys() success " + eId + " -> ***" + request.responseText + "***" ); // => Here is the problem:
// => eId prints out as expected
// => but request.responseText is the same for both calls
var myJSON = JSON.parse(request.responseText); // => so I always get the same JSON
} // success
}); // request
})(eId) // use closure.
}); // each
}
2
Answers
I changed my code, and use
You could try using Promise.all to get all the data then manipulate them, please see this sample code
First a function to get the ids from DOM nodes
Then a function to get the urls given the ids
Then the function to get the data
Finally how to consume the data obtained from calling the previous function
I have not tried this code just write based on what is shown in your example,