With async:set to false, the function is returning the correct value. However it blocks the browser. I’ve tried to add callbacks but it not returning the correct value!
function find_route(array_bustops){
var myresults;
$.ajax({
type: 'POST',
async: true, //with async:false it works
url: 'find_routenum.php',
data:{
array_bustops:JSON.stringify(array_bustops)
},
dataType:'json', //html,xml
success: function(my_results){
myresults=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.');
}
});
return myresults;
}
WITH CALLBACK:
function find_route(array_bustops,callback){
var myresults;
$.ajax({
type: 'POST',
async: true, //with async:false it works
url: 'find_routenum.php',
data:{
array_bustops:JSON.stringify(array_bustops)
},
dataType:'json', //html,xml
success: function(my_results){
callback(array_bustops,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.');
}
});
return myresults;
}
function find_route2(myresults){
return myresults;
}
And then i call the function as follows:
arr_one=find_route(arr,find_route2)
but arr_one returns undefined.
EDIT: it still is not working with async:set to true
arr_one=find_route(arr,find_route2)
this got nothing to do with async but with the architecture of your code.
you declare myresults in the scope of find_route, when you call find_route the function return the value of myresults who is undefined because you delcare it only.
Try to declare var myresults=’somevalue’; in your function
Now your function return ‘somevalue’
This happen because the call to ajax method will not stop the function execution and the success method will be executed way after find_route is called and returned just put a console.log in there you’ll see that it will get log eventually when the success is called.
It work when async false is set because async false as you discover stop the function execution from returning before the ajax call is back
Edit: possible solution