In This Chapter
Understanding AJAX
Using JavaScript to manage HTTP requests
Creating an XMLHttpRequest object
Building a synchronous AJAX request
Retrieving data from an AJAX request
Managing asynchronous AJAX requests
If you have been following the Web trends, you have no doubt heard of AJAX. This expertise has generated a lot of interest. Depending on whom you listen to, it is either going to change the Internet or it is a lot of overblown hype. In this mini-book, I show you what AJAX really is, how to use it, and how to use a particular AJAX library to supercharge your Web pages.
The first thing is to figure out exactly what AJAX is and what it is not. It is not:
✦ A programming language: It isn’t one more language to learn along with the many others you encounter.
✦ New: Most of the technology used in AJAX isn’t really all that new; it’s the way the technology’s being used that’s different.
✦ Remarkably different: For the most part, AJAX is about the same things you’ll see in the rest of this book: building compliant Web pages that interact with the user.
So you’ve got to be wondering why people are so excited about AJAX. It’s a relatively simple thing, but it has the potential to change the way people think about Internet development. Here’s what it really is:
✦ Direct control of client-server communication: Rather than the automatic communication between client and server that happens with Websites and server-side programs, AJAX is about managing this relationship more directly.
✦ Use of the XMLHttpRequestobject: This is a special object that has been built into the DOM[E1] of all major browsers for some time, but it was not used heavily. The real innovation of AJAX was finding creative (perhaps unintentional) uses for this heretofore virtually unknown utility.
✦ A closer relationship between client-side and server-side programming: Up to now, client-side programs (usually JavaScript) did their own thing, and server-side programs (PHP) operated without too much knowledge of each other. AJAX helps these two types of programming work together better.
✦ A series of libraries that facilitate this communication: AJAX isn’t that hard, but it does have a lot of details. Several great libraries have sprung up to simplify using AJAX technologies. You’ll find AJAX libraries for both client-side languages like JavaScript, and server-side languages like PHP.
Let’s say you’re making an online purchase with a shopping cart mechanism. In a typical (pre-AJAX) system, an entire Web page is downloaded to the user’s computer. There may be a limited amount of JavaScript-based interactivity, but anything that requires a data request needs to be sent back to the server. For example, if you’re on a shopping site and you want more information about that fur-lined fishbowl you’ve had your eye on, you might click on the “more information” button. This causes a request to be sent to the server, which builds an entire new Web page for you containing your new request. Every time you make a request, the system builds a whole new page on the fly. The client and server have a long-distance relationship.
In the old days when you wanted to manage your Web site’s content, you had to refresh each Web page — time-consuming to say the least. However, with AJAX, you can update the content on a page without refreshing the page[1]. Instead of the server sending an entire page response just to update a few words on the page,
the server just sends the words you want to update and nothing else[2].
If you’re using an AJAX-enabled shopping cart, you might still click on the fish bowl image. An AJAX request goes to the server and gets information about the fish bowl, which is immediately placed in the current page, without requiring a complete page refresh.
AJAX technology allows you to send a request to the server, which can then change just a small part of the page. With AJAX, you can have a whole bunch of smaller requests happening all the time, rather than a few big ones that rebuild the page in large distracting flurries of activity.
To the user, this makes the Web page look more like traditional applications. This is the big appeal of AJAX: It allows Web applications to act more like desktop applications, even if these Web applications have complicated features like remote database access. Google’s Gmail was the first major application to use AJAX, and it blew people away because it felt so much like a regular application inside a Web browser[3].
AJAX Spelled Out
Technical people love snappy acronyms. There’s nothing more intoxicating than inventing a term. AJAX is one term which has taken on a life of its own. Like many computing acronyms, it may be fun to say, but it doesn’t really mean much. AJAX stands for Asynchronous JavaScript And XML. Truthfully, these terms were probably chosen to make a pronounceable acronym rather than for their accuracy or relevance to how AJAX works.
A is for asynchronous
An asynchronous transaction (at least in AJAX terms) is one in which more than one thing can happen at once. For example, you can make an AJAX call process a request while the rest of your form is being processed. AJAX requests do not absolutely have to be asynchronous, but they usually are. When it comes to Web design, asynchronous means that you can independently send and receive as many different requests as you want. Data may start transmitting at any time without having any effect on other data transmissions. You could have a form that saves each field to the database as soon as it’s filled out. Or perhaps a series of drop-down lists that generates the next drop-down list based upon the value you just selected. (It’s OK if this doesn’t make sense right now. It’s not an important part of understanding AJAX, but vowels are always nice in an acronym.)
In this chapter, I show you how to do both synchronous and asynchronous versions of AJAX.
J is for JavaScript ---- If you want to make an AJAX call, you simply write some JavaScript code that simulates a form. You can then access a special object hidden in the DOM (the XMLHttpRequestobject) and use its methods to send that request to the user. Your program acts like a form, even if there was no form there. In that sense, when you’re writing AJAX code, you’re really using JavaScript. Of course, you can also use any other client-side programming language that can speak with the DOM, including Flash and (to a lesser extent) Java. JavaScript is the dominant technology, so it’s in the acronym.
A lot of times, you also use JavaScript to decode the response from the AJAX request.
A is for . . . and?
I think it’s a stretch to use “and” in an acronym, but AJX just isn’t as cool as AJAX. I guess they didn’t ask me.
And X is for . . . data
The X is for XML, which is one way to send the data back and forth from the server.
Since the object we’re using is the XMLHttpRequestobject, it makes sense that it requests XML. It can do that, but it can also get any kind of text data. You can use AJAX to retrieve all kinds of things:
✦ Plain old text: Sometimes you just want to grab some text from the server. Maybe you have a text file with a daily quote in it or something.
✦ Formatted HTML: You can have text stored on the server as a snippet of HTML/XHTML code and use AJAX to load this page snippet into your browser. This gives you a powerful way to build a page from a series of smaller segments. You can use this to reuse parts of your page (say headings or menus) without duplicating them on the server.
✦ XML data: XML is a great way to pass data around. (That’s what it was invented for.) You might send a request to a program that goes to a data-base, makes a request, and returns the result as XML.
✦ JSON data: A new standard called JSON (JavaScript Object Notation) is emerging as an alternative to XML for formatted data transfer. It has some interesting advantages.
Making a Basic AJAX Connection
AJAX uses some technical parts of the Web in ways that may be unfamiliar to you. Read through the rest of this chapter so you know what AJAX is doing, but don’t get bogged down in the details. Nobody does it by hand!
(Except people who write AJAX libraries or books about using AJAX.) In Chapter 2 of this minibook I show a library that does all the work for you. If all these details are making you misty-eyed, just skip ahead to the next chapter and come back here when you’re ready to see how all the magic works. The basic AJax.html program shown in Figure 1-1 illustrates AJAX at work. When the user clicks on the link, a small pop-up shown in Figure 1-2 appears.
If you don’t get the joke, you need to go rent Monty Python and the Holy Grail[i]. It’s part of the geek culture. Trust me. In fact, you should really own a copy.
It’s very easy to make JavaScript pop up a dialog, but the interesting thing here is where that text comes from. The data is stored on a text file on the server. Without AJAX, there is no easy way to get data from the server without reloading the entire page.
You might claim that HTML frames allow you to pull data from the server, but frames have been deprecated in XHTML because they cause a lot of other problems. You can use a frame to load data from the server, but you can’t do all the other cool things with frame-based data that you can with AJAX. Even if frames were allowed, AJAX is a much better solution most of the time. You won’t be able to run this example straight from the CD-ROM. Like PHP, AJAX requires a server to work properly. If you want to run this program, put it in a subdirectory of your server and run it through localhost as you do for PHP programs.
This particular example uses a couple of shortcuts to make it easier to understand:
✦ It isn’t fully asynchronous. The program will pause while it retrieves data. As a user, you won’t even notice this, but as you’ll see, this can have a serious drawback. It’s a bit simpler, so I start with this example and then extend it to make the asynchronous version.
✦ It isn’t completely cross-browser-compatible. The AJAX technique I use in this program works fine for IE 7 and all versions of Firefox (and most other standards-compliant browsers). It does not work correctly in IE 6 and earlier. I recommend you use jQuery or another library (described in Chapter 2 of this minibook) for cross-browser compatibility.
Look over the code, and you’ll find it reasonable enough:
<!DOCTYPE html PUBLIC
“-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html lang = “EN” xml:lang = “EN” dir = “ltr”>
<head>
<meta http-equiv=”content-type” content=”text/xml; charset=utf-8” />
<title>Basic AJAX</title>
<script type = “text/javascript”>
//<![CDATA[
function getAJAX(){
var request = new XMLHttpRequest();
request.open(“GET”, “beast.txt”, false);
request.send(null);
if (request.status == 200){
//we got a response – por que 200 significa a conexão estabelecida.
alert(request.responseText);
} else {
//something went wrong
alert(“Error- “ + request.status + “: “ + request.statusText);
} // end if
} // end function
//]]>
</script>
</head>
<body>
<h1>Basic AJAX</h1>
<form action = “”>
<p>
<button type = “button”
onclick = “getAJAX()”>
Summon the vicious beast of Caerbannog
</button>
</p>
</form>
</body>
</html>
Building the HTML form
You don’t absolutely need an HTML form for AJAX, but I have a simple one here. Note that the form is not attached to the server in any way.
<form action = “”>
<p>
<button type = “button”
onclick = “getAJAX()”>
Summon the vicious beast of Caerbannog
</button>
</p>
</form>
This code uses a button, and the button is attached to a JavaScript function called getAJAX().
All you really need is some kind of structure that can trigger a JavaScript function.
AJAX isn’t a complex technology, but it does draw on several other technologies. You may need to look over the JavaScript chapters in Book IV if this material is unfamiliar to you. Although these examples don’t require PHP, they do involve server-side responses like PHP does, so AJAX is usually studied by people already familiar with both JavaScript and PHP.[4]
HTML XHTML and CSS All-in-One Desk Reference for Dummies
[2] O servidor apenas envia as palavras que deseja atualizar e nada mais.
[3] O Gmail do Google foi o primeiro aplicativo importante a usar o AJAX, e isso despertou as pessoas porque se tinha a sensação de estar usando um aplicativo dentro de um navegador da Web.
[4] Então AJAX geralmente é estudado por pessoas que já estão familiarizadas com JavaScript e PHP.
No comments:
Post a Comment