I have a javascript functions that fetches some JSON from a PHP. When I get the JSON my plan is to parse it and load it in to an array and then return that array so that I can use the data anywhere.
This is the ajax function:
function get_ajax(route_val){
$.ajax({
url: "ajax.php",
dataType: 'json',
data: {
route: route_val
},
success: function(result) {
if(result.error == true){
alert(result.message);
}else{
$.each(result, function(key1, value1){
//console.log(key1 + ":" + value1);
returnarray[key1] = value1;
});
return returnarray;
}
}
});
}
</script>
If I then try to define say var arr = get_ajax(‘1’), arr is going to be empty. I can alert and console.log stuff from the array from inside the function but returning it returns nothing.
It does not seem to exist outside of the function.
Any ideas?
You are using
Ajaxincorrectly, the idea is not to have itreturnanything, but instead hand off the data to something called acallbackfunction, which handles the data.IE:
returning anything in the submit handler will not do anything, you must instead either hand off the data, or do what you want with it directly inside the success function.