As Charlie mentioned when you use async in a loop or something with a callback you can't use the loop variable as a direct closure.
A simple solution is as Robert mentions to use Promise.all
since $.ajax
returns a promise like object. It would look something like this:
var partsOfStr = [james, mary, kingkong];
Promise.all(
partsOfStr.map(
function(part){
return $.ajax({
url: 'http://mp02.mybitmp.org/friendzone/getsurvey.php?Name=' + part,
dataType: 'json',
})
.then(
function(result){
console.log("result for "+part+" received");
return result;
}
)
}
)
).then(
function(results){
console.log("All results received",results.length);
}
).catch(
function(err){
console.warn("Something went wrong:",err);
}
);
If you want to support browsers that don't have native promises or don't want to polyfil it you can use jQuery.when instead of Promise.all:
var partsOfStr = [james, mary, kingkong];
$.when.apply(
$,
partsOfStr.map(
function(part){
return $.ajax({
url: 'http://mp02.mybitmp.org/friendzone/getsurvey.php?Name=' + part,
dataType: 'json',
})
.then(
function(result){
console.log("result for "+part+" received");
return result;
}
)
}
)
).then(
function(results){
console.log("All results received",results.length);
}
).catch(
function(err){
console.warn("Something went wrong:",err);
}
);