Wednesday, 28 March 2018

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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...