Return AJAX returnback return

For example, I have a function:

var f1 = function(arg) { var a; $.ajax({ ... success: function(data) { a = f2(data); //return a; } }); //return a; } var f3 = function() { a = f1(arg); } 

How can I return a after AJAX receives data in f1 ?

+7
source share
4 answers

You cannot return the result of your ajax request, since the request is asynchronous (and synchronous ajax requests are a terrible idea).

Best would pass your own callback to f1

 var f1 = function(arg, callback) { $.ajax({ success: function(data) { callback(data); } }); } 

Then you call f1 as follows:

 f1(arg, function(data) { var a = f2(data); alert(a); } ); 
+15
source

Short, simple answer: you cannot.

You can make a global, but you will have problems with synchronization.

It's better:

  • Pass a callback to run in Ajax success or
  • Use jQuery .when / .then construct or
  • Just do the work in the callback.
  • (Yes, you could make a synchronous call. Please do not do this.)
+2
source

The easiest way to do this is to make ajax synchronous call. The value in your function f1 configures the ajax call with asynchronous: false so that the function does not move until the call and the returned data end.

0
source

It seems you need to make ajax synchronous call. You can do it like this:

 $.ajax({ ... async: false, success: ... }); return a; 

Thus, JS execution is paused until the call returns and the success function is executed.

Of course, there is a problem with synchronization calls. It is best to reorganize your code so that you do what you need to do with the variable a in the success callback.

Based on this idea, suppose your f3 function was something like this:

 var f3 = function() { a = f1(arg); alert(a); //ie "do something" with "a" } 

Instead, you can do this:

 var f3 = function() { f1(arg); } var f3_callback = function(a) { alert(a); //ie "do something" with "a" } 

So your success function will look like this:

 success: function(data) { a = f2(data); f3_callback(a); } 

Hope this is clear!

0
source

All Articles