How can I take advantage of callback functions for asynchronous XMLHttpRequest?

Callbacks are pretty simple and nifty! Because of the nature of AJAX calls, you don’t block execution of your script till your request is over (it would be synchronous then). A callback is simply a method designated to handle the response once it gets back to your method.

Since javascript methods are first class objects, you can pass them around like variables.

So in your example

getText = function(url, callback) // How can I use this callback?
{
    var request = new XMLHttpRequest();
    request.onreadystatechange = function()
    {
        if (request.readyState == 4 && request.status == 200)
        {
            callback(request.responseText); // Another callback here
        }
    }; 
    request.open('GET', url);
    request.send();
}

function mycallback(data) {
   alert(data);
}

getText('somephpfile.php', mycallback); //passing mycallback as a method

If you do the above, it means you pass mycallback as a method that handles your response (callback).

EDIT

While the example here doesn’t illustrate the proper benefit of a callback (you could simply put the alert in the onReadyStateChange function after all!), re usability is certainly a factor.

You have to keep in mind that the important thing here is that JS methods are first class objects. This means that you can pass them around like objects and attach them to all sorts of events. When events trigger, the methods attached to those events are called.

When you do request.onreadystatechange = function(){} you’re just assigning that method to be called when the appropriate event fires.

So the cool thing here is that these methods can be reused. Say you have an error handling method that pops up an alert and populates some fields in the HTML page in the case of a 404 in the AJAX request.

If you couldn’t assign callbacks or pass methods as parameters, you’d have to write the error handling code over and over again, but instead all you have to do is just assign it as a callback and all your error handling will be sorted in one go.


Leave a Comment