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?
$.ajax
is asynchronous, so in order to get the data back you will need to pass a callback to your doAjaxRequest
function. I've added a callback parameter to doAjaxRequest
and instead of using the result of doAjaxRequest
the code that handles the response is in the callback function.
// some function that needs ajax data
function myFunction(invoice) {
// pass the invoice data to the ajax function
doAjaxRequest(invoice, 'invoice', function (result) {
console.dir(result);
});
}
// build generic ajax request object
function doAjaxRequest(data, task, callback) {
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
callback(data);
}
});
}
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