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:

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: