Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ajax-- returning data to calling function

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?

like image 410
julio Avatar asked Oct 10 '12 22:10

julio


1 Answers

$.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);
        }
    });
}
like image 164
Brigham Avatar answered Oct 16 '22 16:10

Brigham