Saturday 3 November 2018

javaScript return Function with ajax

The problem is that ajax requests are asynchronous, so the function is returning immediately after kicking off the jQuery.ajax call, and at that point goodPassword is still undefined.


Instead you need to do something like this:


function foo(callback) {
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;
}
callback(goodPassword);
}});
}

You would then call the function like this:


foo(function(goodPassword) {
console.log('goodPassword is ' + 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...