I am bit confused on why I am getting 'msg' is undefined error (alert(msg) line) in below code. if I have at least one incorrect address ( address: 0) then I would expect below code to set inValidUser =1 and also set msg variable and then break the the loop. However, I then get a javascript error " Error: 'msg' is undefined." Any ideas?
function test(userData) {
var myArr = [];
var i;
for (i = 1; i <= 3; i++) {
myArr.push(
jQuery.ajax({
type: "GET",
url: "http:/c.html/" + i,
});
);
}
$.when.apply($, myArr).done(function() {
var i = 0;
var invalidUser = 0;
var tableData = [];
$.each(arguments, function (idx, args) {
if (args[0].address === 0) {
invalidUser = 1;
var msg = "User Address " + userData[j].address + " not correct";
return false;
} else {
tableData.push({
name: userData[i].firstname,
age: userData[i].age
});
}
i++;
});
if (invalidUser `enter code here`=== 1) {
alert(msg);
} else {
addTableData(tableData);
}
}).fail (function (jqXHR, textStatus) {
//oops..failed
});
}
msgvariable is not in the scope of youralert(). Define it at the top ofapply().done(), and remove thevarkeyword inside the$.each()varinside a function.