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 Ajax incorrectly, the idea is not to have it return anything, but instead hand off the data to something called a callback function, which handles the data.
IE:
function handleData( responseData ) {
// do what you want with the data
console.log(responseData);
}
$.ajax({
url: "hi.php",
...
success: function ( data, status, XHR ) {
handleData(data);
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With