Friday 26 July 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...