Possible Duplicate:
How to return the response from an AJAX call from a function?
I have a function that reads numerical data from a file online. While the file is retrieved correctly (proven by the value displayed by the alert), when I try to set it to output and then return output, I get an undefined result.
I tried to go through scoping tutorials to no avail. What am I doing wrong?
function readFileFromWeb() {
var output;
jQuery.get('http://domain.com', function(data) {
alert(data);
output = data;
});
return output;
}
Here’s how it should be done, via a callback function.
This is because
jQuery.getis an asynchronous function i.e. it doesn’t block while executing and thus returns immediately. And that is infact the reason why thejQuery.getfunction requires a callback function, so that it fires your callback function once the AJAX query has returned.Thus, you will need to use the same callback pattern when implementing your own
readFileFromWebfunction.