I’ve written a simple generic ajax function that can be called by multiple functions in my script. I’m not sure how to get the data returned to the ajax function back to the caller.
// some function that needs ajax data
function myFunction(invoice) {
// pass the invoice data to the ajax function
var result = doAjaxRequest(invoice, 'invoice');
console.dir(result); // this shows `undefined`
}
// build generic ajax request object
function doAjaxRequest(data, task) {
var myurl = 'http://someurl';
$.ajax({
url: myurl + '?task=' + task,
data: data,
type: 'POST',
success: function(data) {
console.dir(data); // this shows good data as expected
return data; // this never gets back to the calling function
}
});
}
Is there a way to return the ajax data to the calling function?
$.ajaxis asynchronous, so in order to get the data back you will need to pass a callback to yourdoAjaxRequestfunction. I’ve added a callback parameter todoAjaxRequestand instead of using the result ofdoAjaxRequestthe code that handles the response is in the callback function.