Reputation: 151
This question is maybe related to the question i asked here: Jquery ajax request with async:true does not return value.
Now, i'm facing another problem. How do i retrieve the value from the callback function?
function find_bus_route(array_bustops,callback){
$.ajax({
type: 'POST',
async: true,
url: 'find_routenum.php',
data:{
array_bustops:JSON.stringify(array_bustops)
},
dataType:'json', //html,xml
success: function(my_results){
callback(my_results);
},
error:function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}
}
});
}//end function
var arr_one;
find_bus_route(arr_bus,function (data){
arr_one=data;
alert(arr_one) //has correct value
}
alert (arr_one) //-->This returns undefined..
arr_one seems to be out of scope.
if(arr_one == arr_two){
//do something.
}
actually what i'm trying to do is this: assuming there is no callback and async is set to false and the function find_bus_route is returning a value.
var arr_one=find_bus_route(arr_stop1);
var arr_two=find_bus_route(arr_stop2);
if(arr_one==arr_two){
//do something
}
else {
//do something
};
Upvotes: 1
Views: 1039
Reputation: 9822
Since you call an external page aynchronously, you do not have the result immediately (depending on server/network load).
In your code, the second alert (which displays undefined
) is executed just after the AJAX call (response might not be obtained). The other one is executed when the JSON response is fetched. You can use return value only in success
callback.
I think you should explain us exactly what are you trying to do.
EDIT :
I think what you need is called deferred object, see this.
With jQuery.when()
you can wait for two asynchronous calls. The first example is exactly what you ask. In the when callback, you compare the two results.
Upvotes: 1
Reputation: 171679
First "A" in ajax is for asynchronous. The ajax hasn't completed when your "if" fires. You need to move it into your success callback
Upvotes: 2