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 }
ajax({ async: true, contentType: 'application/json; charset=utf-8', type: "POST", dataType: 'json', data: JSON. stringify(arrays), url: "MyHandler. ashx", success: function (result) { b = true; }, error: function () { alert('Error occurred'); } });
You can't return "true" until the ajax requests has not finished because it's asynchron as you mentioned. So the function is leaved before the ajax request has finished.
The A in Ajax stands for asynchronous. That means sending the request (or rather receiving the response) is taken out of the normal execution flow. In your example, $. ajax returns immediately and the next statement, return result; , is executed before the function you passed as success callback was even called.
It receives the returned data and the value of dataType , and must return the (possibly altered) data to pass on to success . success callback option is invoked, if the request succeeds. It receives the returned data, a string containing the success code, and the jqXHR object.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With