The callback function - AJAX

By now, then, you have learned how to create an instance of an XMLHTTPRequest object, declare the identity of a callback function, and prepare and send an asynchronous server request.You also know which property tells you when the server response is available for use.

Let’s look at our callback function, responseAjax().

First, note that this function is called every time there is a change in thevalue of the onreadystatechange property. Usually, then, when this function is called, it is required to do absolutely nothing because the value of the readyState property has not yet reached 4 and we therefore know that the server request has not completed its processing. We can achieve this simply by using a JavaScript if statement:

In addition to checking that the server request has completed, we also want to check the HTTP response status code to ensure that it is equal to 200, indicating a successful response to our asynchronous HTTP request.

Referring quickly back to Table we can see that our XMLHTTPRequest object myRequest has two properties that report the HTTP status response.These are


which contains the status response code, and


containing the reason phrase.

We can employ these properties by using a further loop:

This code introduces an else clause into our if statement. Any serverstatus response other than 200 causes the contents of this else clause to be executed, opening an alert dialog containing the text of the reason phrase returned from the server.

Using the Callback Function
So how do we go about calling our callAjax() function from our HTML page? Let’s see an example. Here’s the code for a simplified form in an HTML page:

We’ll launch the function using the onBlur event handler of a text inputfield in a form:

The onBlur event handler is activated when the user leaves the field inquestion. In this case, when the user leaves the field, callAjax() will be executed, creating an instance of the XMLHTTPRequest object and making an asynchronous server request to

That doesn’t sound very useful. However, what if we were to now make a slight change to the code of callAjax()?

Now we can see that, as the user leaves the form field myname, the value she had typed into that field would be passed to the server via our asynchronous request. Such a call may, for example, check a database to verify the existence of the named person, and if so return information to populate other fields on the form.

The result, so far as the user is concerned, is that she sees the remaining fields magically populated with data before submitting—or even completing—the form.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

AJAX Topics