Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
81
rated 0 times [  88] [ 7]  / answers: 1 / hits: 21836  / 13 Years ago, fri, january 27, 2012, 12:00:00

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?


More From » ajax

 Answers
7

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

[#87768] Thursday, January 26, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
koltonadolfow

Total Points: 71
Total Questions: 118
Total Answers: 102

Location: Vietnam
Member since Sun, Oct 18, 2020
4 Years ago
;