Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function that return a value from ajax call request [duplicate]

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 } 
like image 324
Mohit Pandey Avatar asked Apr 06 '13 05:04

Mohit Pandey


People also ask

How can a function return a value in ajax?

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'); } });

Can we return a value from ajax call?

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.

How do I return a response from ajax?

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.

What does ajax request return?

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.


1 Answers

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 } 
like image 134
su- Avatar answered Oct 18 '22 11:10

su-