Search code examples
javascriptjqueryajaxtastypie

$.ajax() callbacks are not bound to their specific request?


The code is very complex so i have simplified below in order to confirm if the behavior i am experiencing is normal or due so some other error i have made in the code.

I have two separate ajax requests that each have their own unique call back. I do not care which one completes first and one has no dependency on the other

function ajax(url, cbS){
    $.ajax({
        url: url,
        contentType: 'application/json',
        dataType: 'json', 
        success: function(data){
            cbS(data)
        },
    });
}

function callbackSuccess1(data){
    $('#div1').html(data)
}
function callbackSuccess2(data){
    $('#div2').html(data)
}

//request#1
ajax(myapiurl+'&peram1=100', callbackSuccess1);
//request#2
ajax(myapiurl+'&peram2=200', callbackSuccess2);

The problem: Sometimes callbackSuccess1 gets the data intended for request#2 and vice versa.

It seems that which ever request completes first fires callbackSuccess1 and the second to complete fires callbackSuccess2.

I need the callback to be bound to it's specific request so that regardless of the order in which they complete each request fires it's proper callback.

OTHER INFO: My backed is django-tastypie, at this point i am thinking that tastypie is somehow messing up the response. That is the only logical conclusion, given that the javascript seems to be immutable.

The proof that this is actually occurring is that when i inspect the responce on request#1 the data objects are clearly intended for request#2...

CONCLUSION: Thanks for confirming that 'each invocation of your ajax() function will create it's own closure'. This was what i thought was going wrong. I found the problem in my API. I was doing some funky stuff and it looks like I had a variable that was not getting trashed in time causing the API to return the wrong data if the first request took longer than the second.


Solution

  • The only issue I see with the code you have included is that the function argument is cbS, but you are calling cbs(data) - note the different capitalization.

    Other than that, each invocation of your ajax() function will create it's own closure and have it's own arguments and those arguments will be preserved separately for the internal success callback. This is an important capability in javascript and it works. It does not get the arguments of one call confused with the callback of another as long as you are not using any global variables or state that might change during the execution of the asynchronous ajax call.