In an attempt to make my jQuery code modular, i.e. reusable, I've placed an ajax() function inside of another function fetch_ajax(). I'm trying to call fetch_ajax() with parameters from other places, which should simply run the contained ajax() and return the response.
But that's not happening - instead, fetch_ajax() apparently returns false too quickly to the caller and doesn't wait until ajax() has completed the request and gotten a response.
Here's the code:
The fetch_ajax() function
function fetch_ajax(url) {
$.ajax({
type: 'GET',
url: url,
success: function(response) {
return response;
}
});
}
The calling function:
function caller() {
response = fetch_ajax('script.php');
alert(response); //this is always 'undefined'
}
In fetch_ajax(), I've tried not directly returning response from within ajax(), but writing it to a variable, and returning that variable after ajax() - that didn't work either (same result).
When I place a 2nd alert right before return response; inside of the ajax() function, I'm seeing that one fire AFTER the one inside caller(). So I'm thinking that somehow, fetch_ajax() doesn't wait for the contained function to execute before it returns false.
What am I doing wrong?
Thank you.