HTML, XHTML and CSS All-In-One for Dummies - Andy Harris [277]
Of course, I could do a lot more with the data. If it’s already formatted as HTML code, I can use the innerHTML DOM tricks described in Book IV to display the code on any part of my page. It might also be some other type of formatted data (XML or JSON) that I can manipulate with JavaScript and do whatever I want with.
All Together Now — Making the Connection Asynchronous
The synchronous AJAX connection described in the previous section is easy to understand, but it has one major drawback: The client’s page stops processing while waiting for a response from the server. This doesn’t seem like a big problem, but it is. If aliens attack the Web server, it won’t make the connection, and the rest of the page will never be activated. The user’s browser will hang indefinitely. In most cases, the user will have to shut down the browser process by pressing Ctrl+Alt+Delete (or the similar procedure on other OSs). Obviously, it would be best to prevent this kind of error.
That’s why most AJAX calls use the asynchronous technique. Here’s the big difference: When you send an asynchronous request, the client keeps on processing the rest of the page. When the request is complete, an event handler processes the event. If the server goes down, the browser will not hang (although the page probably won’t do what you want).
In other words, the readyState property is like looking at the basket’s progress. The basket could be sitting there empty because you haven’t begun the process. It could be going up to the window, being filled, coming back down, or it could be down and ready to use. You’re only concerned with the last state, because that means the data is ready.
I didn’t include a figure of the asynchronous version, because to the user, it looks exactly the same as the synchronous connection. Be sure to put this code on your own server and check it out for yourself.
The asynchronous version looks exactly the same on the front end, but the code is structured a little differently:
“-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
Asynchronous AJAX transmission
Setting up the program
The general setup of this program is just like the earlier AJAX example. The HTML is a simple button that calls the getAJAX() function.
The JavaScript code now has two functions. The getAJAX() function sets up the request, but a separate function (checkData()) responds to the request. In an asynchronous AJAX model, you typically separate the request and the response in different functions.
Note that in the JavaScript code, I made the XMLHttpRequest object (request) a global variable by declaring it outside any functions. I generally avoid making global variables, but it makes sense in this case because I have two different functions that require the request object.
Building the getAJAX() function
The getAJAX() function sets up and executes