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.responseTextin 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
}
eidvalues isn't something we can know. Just check yournetworktab in Chrome developer tools to make double sure that you're making different requestsrequestvariable is global, therefore being override by your second call. So when it reach the success callback, it is not the same as what it was when it started.request.responseTextin the first place? Isn'tjsonDatathe response you want?dataType: 'json'and jQuery will parse it automatically and put the result injsonData.Content-type: application/json