The callback needs to identify the result of the request and proceed with the handling of the data returned from the web server. Callback functions generally also serve as a delegator, meaning that it will delegate the processing of other code to other areas of your JavaScript application.

Example

We will use the following HTML for the examples listed below.

Without Callback

In the previous example, we set an event handler for the onreadystatechange event as our ajax_response() function which will be executed every time the state of the request changes. 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. This is not optimal. The readyState property can have several values:

0 – request not initialized1 – server connection established2 – request received3 – processing request4 – request completed and response is ready

Callback

In the example with the Callback function, we simplified and improved the readability of the code. Most JavaScript frameworks will encourage you to take advantage of functional programming in this manner.