Wednesday 1 May 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

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