Search code examples
javascriptjqueryasynccallback

Asynchronous callbacks


I've written a function which makes an asynchronous request using jQuery.

var Site = {

    asyncRequest : function(url, containerId) {        
        $.ajax({
            url : url,
            onSuccess: function(data){
                $(containerId).html(data);
            }
        });
    }
}

Syntax might be slightly wrong as I'm using notepad, but hopefully you get the idea.

I call the function:

Site.asyncRequest('someurl', container1);
Site.asyncRequest('someurl', container2);

Both requests get sent and processed by the server. Two responses get sent back, which is what I expect. However, I would expect container1 and container2 to contain responses from both requests.

The problem, is that only the last response gets displayed and I can't figure out why. I don't know how the jQuery ajax keeps a track of requests/responses, so maybe this is a problem.

Say I make 5 or 10 requests, how does jQuery ajax know which response is for which request and where does it keep a track of it?

Thank you


Solution

  • This appears to be a Javascript scoping issue. Try the following:

    var Site = {
        asyncRequest: function(url, containerId) {
            (function(theContainer) {
                $.ajax({
                    url: url,
                    onSuccess: function(data) {
                        $(theContainer).html(data);
                    }
                });
            })(containerId);
        }
    };
    

    This creates a separate scope for each function call, so the actual value pointed to by "theContainer" is different for each onSuccess anonymous function.