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