Mastering Ajax, Part 2: Make asynchronous requests with JavaScript and Ajax, continued
|
 |
Visited: 756 |
|
|
| 5.0/5.0 (1 votes total) |
|
|
|
|
by Brett McLaughlin April 18, 2006
|
| Brett McLaughlin |
In recent years, Brett McLaughlin has become one of the most
well-known authors and programmers in the Java and XML communities.
He's worked for Nextel Communications, implementing complex enterprise
systems; at Lutris Technologies, actually writing application servers;
and most recently at O'Reilly Media, Inc., where he continues to write
and edit books that matter.
|
| Brett McLaughlin
has written 5 articles for JavaScriptSearch. |
| View all articles by Brett McLaughlin... |
Listing 14. Check the HTTP status code
function updatePage() {
if (request.readyState == 4)
if (request.status == 200)
alert("Server is done!");
}
|
To add more robust error handling -- with minimal complication -- you might
add a check or two for other status codes; check out the modified version of updatePage() in Listing 15.
Listing 15. Add some light error checking
function updatePage() {
if (request.readyState == 4)
if (request.status == 200)
alert("Server is done!");
else if (request.status == 404)
alert("Request URL does not exist"); else alert("Error: status code is " + request.status); }
|
Now change the URL in your getCustomerInfo()
to a non-existent URL and see what happens. You should see an alert that tells
you the URL you asked for doesn't exist -- perfect! This is hardly going to
handle every error condition, but it's a simple change that covers 80 percent
of the problems that can occur in a typical Web application.
Reading the response text
Now that you made sure the request was completely processed (through the
ready state) and the server gave you a normal, okay response (through the
status code), you can finally deal with the data sent back by the server. This
is conveniently stored in the responseText
property of the XMLHttpRequest
object.
Details about what the text in responseText
looks like, in terms of format or length, is left intentionally vague. This
allows the server to set this text to virtually anything. For instance, one
script might return comma-separated values, another pipe-separated values (the
pipe is the | character),
and another may return one long string of text. It's all up to the server.
In the case of the example used in this article, the server returns a
customer's last order and then their address, separated by the pipe symbol. The
order and address are both then used to set values of elements on the form; Listing
16 shows the code that updates the display.
Listing 16. Deal with the server's response
function updatePage() {
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseText.split("|");
document.getElementById("order").value = response[0]; document.getElementById("address").innerHTML = response[1].replace(/\n/g, "
"); } else
alert("status is " + request.status);
}
}
|
First, the responseText
is pulled and split on the pipe symbol using the JavaScript split() method. The resulting array of
values is dropped into response.
The first value -- the customer's last order -- is accessed in the array as response[0] and is set as the value of
the field with an ID of "order." The second value in the array, at response[1], is the customer's address
and it takes a little more processing. Since the lines in the address are
separated by normal line separators (the "\n" character), the code
needs to replace these with XHTML-style line separators, <br />s. That's accomplished
through the use of the replace()
function along with a regular expression. Finally, the modified text is set as
the inner HTML of a div in
the HTML form. The result is that the form suddenly is updated with the
customer's information, as you can see in Figure 4.
Figure 4. The Break Neck form after it retrieves customer
data

Before I wrap up, another important property of XMLHttpRequest is called responseXML. That property contains (can
you guess?) an XML response in the event that the server chooses to respond
with XML. Dealing with an XML response is quite different than dealing with
plain text and involves parsing, the Document Object Model (DOM), and several
other considerations. You'll learn more about XML in a future article. Still,
because responseXML commonly
comes up in discussions surrounding responseText,
it's worth mentioning here. For many simple Ajax applications, responseText is all you need, but you'll
soon learn about dealing with XML through Ajax applications as well.
In conclusion
You might be a little tired of XMLHttpRequest
-- I rarely read an entire article about a single object, especially one that
is this simple. However, you will use this object over and over again in each
page and application that you write that uses Ajax. Truth be told, there's
quite a bit still to be said about XMLHttpRequest.
In coming articles, you'll learn to use POST
in addition to GET in your
requests, set and read content headers in your request as well as the response
from the server; you'll understand how to encode your requests and even handle
XML in your request/response model.
Quite a bit further down the line, you'll also see some of the popular Ajax
toolkits that are available. These toolkits actually abstract away most of the
details discussed in this article and make Ajax programming easier. You might
even wonder why you have to code all this low-level detail when toolkits are so
readily available. The answer is, it's awfully hard to figure out what goes
wrong in your application if you don't understand what is going on in
your application.
So don't ignore these details or speed through them; when your handy-dandy
toolkit creates an error, you won't be stuck scratching your head and sending
an email to support. With an understanding of how to use XMLHttpRequest directly, you'll find it
easy to debug and fix even the strangest problems. Toolkits are fine unless you
count on them to take care of all your problems.
So get comfortable with XMLHttpRequest.
In fact, if you have Ajax code running that uses a toolkit, try to rewrite it
using just the XMLHttpRequest
object and its properties and methods. It will be a great exercise and probably
help you understand what's going on a lot better.
In the next article, you'll dig even deeper into this object, exploring
some of its tricker properties (like responseXML), as well as how to use POST requests and send data in several different formats. So start coding
and check back here in about a month. ___________ Re-printed from http://www-128.ibm.com/developerworks/web/library/wa-ajaxintro1.htm with permission. First
published by IBM developerWorks at http://www.ibm.com/developerWorks/ |