Helping ordinary people create extraordinary websites!

AJAX Callback Function

The AJAX callback function - the function we assign as the onreadystatechange event handler - is the central part of our AJAX requests. The callback function is responsible for checking the progress of requests, identifying the result of the request and handling data returned from the server. Callback functions also serve as delegators, handing off to other areas of your application code.

Inline lambda functions

In our previous example, we defined the response handling function and referenced it as the callback:

function ajax_request() {
// ...
xhrobj.onreadystatechange = ajax_response;

function ajax_response() {
// ...

However, more often than not, we will only need the function within that single context, and should define it inline as a lambda function. Instead of referencing a new function, we can define one within the current scope:

xhrobj.onreadystatechange = function() {
// ...

This can save code, and improve the readability of your code. Most JavaScript frameworks will also encourage you to take advantage of functional programming in this manner.

Working with XMLHttpRequest "ready states"

In the previous example, we have created the ajax_response() function, and by setting the onreadystatechange property of the AJAX object to this function, our function will be called every time the state of the object changes. However, the state of the object - that is, the current progress of the request - changes many times. We use the if(xhrobj.readyState == 4) line to check if the request has finished - a value of 4 represents a completed request. Here are the possible values of the readyState property:

Value Status
0 Uninitialized
1 Open - open() has been called, but not send()
2 Sent - send() has been called
3 Receiving - some data has been received from the server
4 Finished

We are primarily concerned with the finished state.

« Basic AJAX Error Checking »

More AJAX Tutorials:
» AJAX Accessibility for Websites
» Five Ways to Spice Up Your Site with jQuery
» Ajax Wireframing Approaches
» Creating the iPhone Unlock Screen in xHTML, CSS and jQuery
» The obligatory 'My Ajax Tutorial' Post
» Getting Started with AJAX in jQuery
Tell a Friend


Developer Resources