JavaScript Editor Free JavaScript Editor     JavaScript Debugger 

Main Page

Previous Page
Next Page

7.1. Synchronous

Although not nearly as cool as coding an asynchronous client-side application, a synchronous client-side application is nothing to look down at. In fact, it beats the pants off the average web applicationfiguratively speaking, of course, because web applications don't wear pants. Thinking about it, using the XMLHttpRequest object synchronously is actually a good way to expose yourself, also figuratively, to some of the basics.

One of the interesting things about the basics of the XMLHttpRequest object is that these basics are actually basic. Only a few parameters and a few lines of code separate the synchronous from the asynchronous. When you understand that, not much is required to change a synchronous application into an asynchronous application. Don't believe me? Take a look at the XMLHttpRequest object's properties and methods shown in Table 7-1.

Table 7-1. XMLHttpRequest Object Properties and Methods




Terminates the previous outstanding request.


Returns all response headers, labels, and values, as a string.


Returns the value for the provided label.

open("method","url", asynchronous,"username","password")

Opens/assigns a method: GET or POST and, optionally, an asynchronous indicator.


Sends the request with optional content. This content can be either a string or DOM data.

setRequestHeader ("label","value")

Sets a request header label/value pair.


Event handler for asynchronous requests; fires on each change to the readyState property.


Status of the request as an integer.

0 = uninitialize

1 = loading

2 = loaded

3 = interactive

4 = complete


String returned from the server.


XML document returned from the server.


HTTP response code returned from the server.


String message associated with the HTTP a.

Right now, the XMLHttpRequest object might seem like a pile of unrelated parts, but when the individual parts are assembled in the correct sequence, things are different. To prove my point, let's take a look at the JavaScript that uses XMLHTTP to synchronously get a file from the server in Gecko-based browsers such as Firefox, Mozilla, and Flock (see Listing 7-1).

Listing 7-1. Getting a File Synchronously

var objXMLHTTP = new XMLHttpRequest();'GET', 'books.xml', false);

var objXML = objXMLHTTP.responseXML;

The first step is to create an instance of the XMLHttpRequest object using the JavaScript new operator. Next, the open method is invoked using the request method, GET, a destination URL, and a Boolean indicating that the request is not asynchronous. The third and final step is to invoke the send method and assign the responseXML, an XML document, to a variable. And if you're not interested in using XML, there is always the responseText property.

Previous Page
Next Page

JavaScript Editor Free JavaScript Editor     JavaScript Debugger