“Raw” Ajax Example Using the XMLHttpRequest Object

In this section, we use the XMLHttpRequest object to create and manage asynchronous requests.

“Raw”AjaxExampleUsingtheXMLHttpRequest Object

In
this section, we use the XMLHttpRequest
object to create and manage asynchronous requests. The XMLHttpRequest object (which resides on the client) is the layer
between the client and the server that manages asynchronous requests in Ajax
applications. This object is supported on most browsers, though they may
implement it differently—a common is-sue in JavaScript programming. To initiate
an asynchronous request (shown in Fig. 15.5), you create an instance of the XMLHttpRequest object, then use its open method to set up the
request and its send method to initiate the request. We summarize the XMLHttpRe-quest propertiesand methodsinFigs.
15.6–15.7.

Figure
15.5 presents an Ajax application in which the user interacts with the page by
moving the mouse over book-cover images. We use the onmouseover and onmouseout
events (discussed in Chapter 13) to trigger events when the user moves the
mouse over and out of an image, respectively. The onmouseover event calls function getContent
with the URL of the document containing the book’s description. The function
makes this request asynchronously using
an XMLHttpRequest object. When the XMLHttpRequest
object receives the response, the
book description is displayed below the book images. When the user moves the
mouse out of the image, the onmouseout
event calls function clearCon-tent
toclear the displaybox.Thesetasksareaccomplishedwithout
reloadingthe page on the client. You can test-drive this example at test.deitel.com/examples/iw3htp4/ajax/fig15_05/SwitchContent.html.

Asynchronous Requests

The function getContent (lines 19–35) sends the asynchronous request. Line 24
creates the XMLHttpRequest object, which manages the asynchronous request. We store
the object in the global variable asyncRequest
(declared at line 16) so that it can be accessed any-where in the script.

Line
28 calls the XMLHttpRequest
open method to prepare an asynchronous GET request. In this example, the url parameter specifies the address of an HTML document
containing the description of a particular book. When the third argument is true, the request is
asynchronous. The URL is passed to function getContent
in response to the onmouseover
eventforeach
image.Line29sends
theasynchronous request totheserverby
calling XMLHttpRequest
send method. The argument null indicates that this request is not submitting data in
the body of the request.

Exception Handling

Lines
22–34 introduce exception handling.
An exception is an indication of a
problem that occurs during a program’s execution. The name “exception” implies
that the problem occurs infrequently—if the “rule” is that a statement normally
executes correctly, then the “excep-tion to the rule” is that a problem occurs.
Exception handling enables you to create applica-tions that can resolve (or
handle) exceptions—in some cases allowing a program to continue executing as if
no problem had been encountered.

Lines
22–30 contain a tryblock,
which encloses the code that might cause an excep-tion and the code that should
not execute if an exception occurs (i.e., if an exception occurs in a statement
of the try block, the remaining code in the try block is skipped). A try blockconsistsofthe
keyword
try followedbya
block ofcode enclosed incurlybraces({}).
If there is a problem sending the request—e.g., if a user tries to access the
page using an older browser that does not support XMLHttpRequest—the try block terminates
imme-diately and a catchblock (also called a catchclause or exception handler) catches (i.e., receives)
and handles an exception. The catch block (lines 31–34)
begins with the key-word catch and is followed by a
parameter in parentheses (called the exception parameter) and a block of code
enclosed in curly braces. The exception parameter’s name (exception in this example) enables the catch block to interact with a caught exception object (for
example, to obtain the name of the exception or an exception-specific error
message via the exception object’s name and message properties). In this case, we simply display our own
error message 'Request
Failed' and terminate the getContent function. The request can fail because a user accesses
the web page with an older browser or the content that is being requested is
located on a different domain.

Callback Functions

The
stateChange function (lines 38–45) is the callback function that is
called when the client receives the response data. Line 27 registers function stateChange as the event handler
for the XMLHttpRequest object’s onreadystatechange
event. Whenever the request makes progress, the XMLHttpRequest
calls the onreadystatechange event handler. This progress
is monitored by the readyState
property, which has a value from 0 to 4. The value 0 indicates that the request
is not initialized and the value 4 indicates that the request is complete—all
the values for this property are summarized in Fig. 15.6. If the request
completes successfully (line 40), lines 42–43 use the XMLHttpRequest object’s responseText property to obtaintheresponse data and place itinthe div elementnamed contentArea (definedatline 81).WeusetheDOM’s
getElementById methodto get this div element, andusethe element’s innerHTML property to placethecontentinthe div.

XMLHttpRequest Object
Properties and Methods

Figures 15.6 and 15.7
summarize some of the XMLHttpRequest object’s properties and methods, respectively. The
properties are crucial to interacting with asynchronous re-quests. The methods
initialize, configure and send asynchronous requests.