I'm calling an AJAX
request inside a for
loop, and I'm expecting to use the iterating variable in the callback function, but it's not retaining the caller value, but the current value.
for (i = 1; i <= numRisks; i++){
var id = window.localStorage['dbIDRisk'+i];
if ($.isNumeric(id)){
$.ajax({
type: "POST",
encoding:"UTF-8",
url:'https://www.example.com/myscript.php',
data: someXdata,
success: function (data) {
window.localStorage['Risk'+i+'PDF'] = 1;
}
});
}
}
It's working fine, the only problem is that, for example, if the iteration variable i = 1
, I'd expect that the localStorage line would be window.localStorage['Risk1PDF'] = 1;
, but instead it's window.localStorage['Risk2PDF'] = 1;
. So the question is, how can I retain the value of i
in the success callback for window.localStorage['Risk'+i+'PDF'] = 1;
?