Friday, July 26, 2019

javaScript return Function with ajax










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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...