Saturday, November 3, 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

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...