Saturday, August 18, 2018

javascript - jQuery: Return data after ajax call success





I have something like this, where it is a simple call to a script that gives me back a value, a string..



function testAjax() {
$.ajax({
url: "getvalue.php",
success: function(data) {

return data;
}
});
}


but if I call something like this



var output = testAjax(svar);  // output will be undefined...



so how can I return the value?
the below code does not seem to work either...



function testAjax() {
$.ajax({
url: "getvalue.php",
success: function(data) {

}

});
return data;
}

Answer



The only way to return the data from the function would be to make a synchronous call instead of an asynchronous call, but that would freeze up the browser while it's waiting for the response.



You can pass in a callback function that handles the result:



function testAjax(handleData) {

$.ajax({
url:"getvalue.php",
success:function(data) {
handleData(data);
}
});
}


Call it like this:




testAjax(function(output){
// here you use the output
});
// Note: the call won't wait for the result,
// so it will continue with the code here while waiting.

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