Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return AJAX callback return [duplicate]

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 get data in f1?

like image 609
DrXCheng Avatar asked Jan 27 '12 23:01

DrXCheng


2 Answers

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

Your best bet will be to pass your own callback into f1

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

Then you'd call f1 like this:

f1(arg, function(data) { 
           var a = f2(data);
           alert(a);
        }
 );
like image 132
Adam Rackis Avatar answered Sep 23 '22 22:09

Adam Rackis


Short, easy answer: you can't.

You could make a a global, but you're subject to timing issues.

Better to either:

  1. Pass in a callback to run in the Ajax success, or
  2. Use jQuery's .when/.then construct, or
  3. Just do the work in the callback.
  4. (Yeah, you could make the call synchronous. Please don't.)
like image 33
Dave Newton Avatar answered Sep 23 '22 22:09

Dave Newton