HTML and CSS Reference
In-Depth Information
3. The request is sent to the server with the send() method.
4. After the request is sent to the server, the object's readyState property keeps
track of the state of the request object; for example, if a request has been made,
the state changes. With an event handler, a callback function can be executed
based on the state of the object. If, for example, the request has been answered
and all the information has been sent by the server, the state of the object can be
checked and a function called to retrieve and handle the data.
Now we will take a closer look at each of the steps to create Ajax communication
between the browser and the server.
18.3.1 Step 1: Create the XMLHttpRequest Object
With the HTTP request/response cycle we discussed at the beginning of the topic, when
the user clicks a link, submits a form, or types an address in the URL, an HTTP connec-
tion is made between the browser and the server. The server's response is to send back
a new or updated page while the user waits. With applications that make asynchronous
calls to the server, there has to be a way to do this without refreshing the page for each
HTTP request. This is done with the XMLHttpRequest object. This object allows Java-
Script to set up a communication channel with the server, exchange data, and update
the page without reloading it. Meanwhile the user continues scrolling, typing, and push-
ing buttons just as he or she would on a desktop application, while Ajax is working with
the server in the background.
The XMLHttpRequest object is supported by all major browsers (Firefox, Chrome,
Opera, and Safari) and is fundamental to all Ajax applications. Internet Explorer 7 comes
with the XMLHttpRequest , but other versions of Internet Explorer support the ActiveX
object, which is not cross-browser compliant. Therefore, when creating a new XMLHttpRe-
quest object, most JavaScript programs use catch and try statements to make sure the object
they get back is compatible with their browser. (See Chapter 7, “Functions,” for a review
of catch and try. ) Example 18.1 demonstrates how to create the XMLHttpRequest object for
most major browsers. See
/* Check browser type and create ajaxRequest object
Put this function in an external .js file and use it for your
Ajax programs
function CreateRequestObject() {
var ajaxRequest; // The variable that makes Ajax possible!
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
// Create the object
Search WWH ::

Custom Search