Search code examples
javascriptajaxfunctionreturn

How to pass on an extra variable along with AJAX response?


Need to run some code only after an AJAX response is received, and I need to pass on a certain variable to the destination function to make it happen.

Tried the below but it doesn't trigger the .done function like it would if we were returning only the ajax(not surprisingly).

function ajax_processor(passthrough_var,ordinary_var)
{
    //Some processing

    return [ passthrough_var, $.ajax({...}) ];
}

ajax_post_processor(array_item)
{
    console.log(array_item[0]);
    console.log(array_item[1]);
}

ajax_processor("Foo","Bar").done(ajax_post_processor);

Solution

  • Have ajax_processor return a promise that resolves to an array containing the response and the passed variable. Something like

    function ajax_processor(passthrough_var,ordinary_var)
    {
        return $.ajax({...}).then(response => [passthrough_var, response]);
    }
    
    function ajax_post_processor(array_item)
    {
        console.log(array_item[0]);
        console.log(array_item[1]);
    }
    
    ajax_processor("Foo","Bar").done(ajax_post_processor);