I can't figure out why goodPassword
always returns undefined
I"m sure it's just a dumb mistake and will appreciate your answer
function foo(){
var goodPassword;
jQuery.ajax({
data: "action=Potato",
url: 'servletPotato',
timeout: 2000,
error: function() {
console.log("Failed to send ajax");
},
success: function(r) {
var data = jQuery.parseJSON(r);
if(data.aprovePassword == "true")
{
goodPassword = true;
}
else
{
goodPassword = false;
}
}
});
return goodPassword;
}
the ajax call is definitely working and data.aprovePassword definitely return from the servlet as "false"
Answer
Because goodPassword
hasn't been assigned anything yet, since the XHR request executes after the function ends and that's why by the end of the function, nothing has been assigned. An alternative function would be:
function foo(successCallback) {
var goodPassword;
jQuery.ajax({
data: "action=Potato",
url: 'servletPotato',
timeout: 2000,
error: function() {
console.log("Failed to send ajax");
},
success: function(r) {
var data = jQuery.parseJSON(r);
if(data.aprovePassword == "true")
{
goodPassword = true;
}
else
{
goodPassword = false;
}
successCallback(goodPassword);
}});
}
No comments:
Post a Comment