Wednesday, May 1, 2019

javascript - function that return a value from ajax call request




I want a function that returns a value from an ajax request. I want to stop javascript execution until the function get its value which is return by ajax asynchronous request.
Something like:



function myFunction() {
var data;
$.ajax({
url: 'url',

data: 'data to send',
success: function (resp) {
data = resp;
},
error: function () {}
}); // ajax asynchronus request
return data; // return data from the ajax request
}

Answer




You need to register a callback function, something like this:



function test() {
myFunction(function(d) {
//processing the data
console.log(d);
});
}

function myFunction(callback) {

var data;
$.ajax({
url: 'url',
data: 'data to send',
success: function (resp) {
data = resp;
callback(data);
},
error: function () {}
}); // ajax asynchronus request

//the following line wouldn't work, since the function returns immediately
//return data; // return data from the ajax request
}

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