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().
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 aremyRequest.status
which contains the status response code, andmyRequest.statusText
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.
AJAX Related Interview Questions
|XML Interview Questions||HTML Interview Questions|
|Java Script Interview Questions||Android Interview Questions|
|CSS Interview Questions||Web Developer Guide Interview Questions|
|XSLT Interview Questions||Java XML Interview Questions|
|XML DOM Interview Questions|
All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.