Search code examples
jquerycallbackbindjquery-callback

Callback functions jQuery AJAX


I want to pass a function with parameters to the success method in an AJAX call using jQuery, that's what I have:

makeAjaxReq(callbackFunction, url, xml, 'POST');

function makeAjaxReq(successMethod, url, xml, method, noAsxml) {
    var headers = { 'X-EWS-ACCEPT': 'ASXML', 'X-Requested-With': 'XMLHttpRequest' };
    var call = $j.ajax({
        type: method,
        url: url,
        data: xml,
        headers: headers,
        success: function (data) {
            if (!noAsxml) {
                var json = parseAsXML(data);
                successMethod(json);
            }
            else {
                successMethod(data);
            }
        },
        error: function (data) {
            var a = 0;
        }
    });

Doing that I receive in my callback function a JSON as a parameter, which is good but, what if I would like to do something like that:

makeAjaxReq(callbackFunction(param1, param2), url, xml, 'POST');

Of course if I do that the callbackFunction will be executed at that moment and not when the AJAX call is done.

I used to do that with the bind function in prototype, something like:

makeAjaxReq(callbackFunction.bind(param1, param2), url, xml, 'POST');

So the goal is to receive in my callback function the JSON, param1 and param2

Do you know a way to do that using jQuery?

Thanks a lot for your time. Kr, Jose


Solution

  • You can do this with partial functions:

    // getCallbackFunction is called immediately and returns a function
    makeAjaxReq(getCallbackFunction(param1, param2), url, xml, 'POST');
    
    // returns a function that accepts one argument and has param1 and param2 in its scope
    function getCallbackFunction(param1, param2) {
        return function(json) {
            // code here has access to param1, param2, and json
        }
    }
    

    Or, you can do a slightly different approach with an anonymous function:

    makeAjaxReq(function(json){ callbackFunction(json, param1, param2) }, url, xml, 'POST');
    

    Here, you have your callback accept three arguments, the first of which is provided on Ajax success and the last two of which are provided at the time the anonymous function is constructed.