I am facing an issue with the data and JavaScript loops while using Ajax to fetch the data. The two loops are working fine with their respective values, but when I include Ajax inside the inner loop, the requests are not being executed in sequence. My requirement is to have the data fetched in the order of the loops. How can this be achieved?
var final = {};
final.reports = ['a','b','c']
final.clients = ['x','y']
final.reportDataJson = [];
for(var i=0;i<final.reports.length;i++){
(function(i,reactthis){
for(var j=0;j<final.clients.length;j++){
(function(i,j,final){
console.log(i+" "+j+" "+final.clients[j])
// this shows correct i j values
$.ajax({
url: url,
cache: false,
success: function(html) {
var reportResponse = {
reportname : final.reports[i],
clientname : final.clients[j],
reporthtml : html,
reportgraph : ''
}
final.reportDataJson.push(reportResponse)
//console.log(i,j)
if( i == final.reports.length-1 && j == final.clients.length-1){
console.log(final.reportDataJson);
}
},
error: function(xhr, status, err) {
if( i == final.reports.length-1 && j == final.clients.length-1){
}
}
})
})
}
})(i,final);
}