Mastering Ajax, Part 1: Introduction to Ajax
Understanding Ajax, a productive approach to building Web sites, and how it works
|New site feature|
|Rate this page|
06 Dec 2005
Five years ago, if you didn't know XML, you were the ugly duckling whom nobody talked to. Eighteen months ago, Ruby came into the limelight and programmers who didn't know what was going on with Ruby weren't welcome at the water cooler. Today, if you want to get into the latest technology rage, Ajax is where it's at.
However, Ajax is far more than just a fad; it's a powerful approach to building Web sites and it's not nearly as hard to learn as an entire new language.
Before I dig into what Ajax is, though, let's spend just a few moments understanding what Ajax does. When you write an application today, you have two basic choices:
- Desktop applications
- Web applications
These are both familiar; desktop applications usually come on a CD (or sometimes are downloaded from a Web site) and install completely on your computer. They might use the Internet to download updates, but the code that runs these applications resides on your desktop. Web applications -- and there's no surprise here -- run on a Web server somewhere and you access the application with your Web browser.
More important than where the code for these applications runs, though, is how the applications behave and how you interact with them. Desktop applications are usually pretty fast (they're running on your computer; you're not waiting on an Internet connection), have great user interfaces (usually interacting with your operating system), and are incredibly dynamic. You can click, point, type, pull up menus and sub-menus, and cruise around, with almost no waiting around.
On the other hand, Web applications are usually up-to-the-second current and they provide services you could never get on your desktop (think about Amazon.com and eBay). However, with the power of the Web comes waiting -- waiting for a server to respond, waiting for a screen to refresh, waiting for a request to come back and generate a new page.
Obviously this is a bit of an oversimplification, but you get the basic idea. As you might already be suspecting, Ajax attempts to bridge the gap between the functionality and interactivity of a desktop application and the always-updated Web application. You can use dynamic user interfaces and fancier controls like you'd find on a desktop application, but it's available to you on a Web application.
So what are you waiting for? Start looking at Ajax and how to turn your clunky Web interfaces into responsive Ajax applications.
When it comes to Ajax, the reality is that it involves a lot of technologies -- to get beyond the basics, you need to drill down into several different technologies (which is why I'll spend the first several articles in this series breaking apart each one of them). The good news is that you might already know a decent bit about many of these technologies -- better yet, most of these individual technologies are easy to learn -- certainly not as difficult as an entire programming language like Java or Ruby.
Here are the basic technologies involved in Ajax applications:
- HTML is used to build Web forms and identify fields for use in the rest of your application.
- DHTML, or Dynamic HTML, helps you update your forms dynamically. You'll use
span, and other dynamic HTML elements to mark up your HTML.
Let's break these down and get a better idea of what each does. I'll delve into each of these more in future articles; for now focus on becoming familiar with these components and technologies. The more familiar you are with this code, the easier it will be to move from casual knowledge about these technologies to mastering each (and really blowing the doors off of your Web application development).
The first object you want to understand is probably the one that's newest to you; it's called
Listing 1. Create a new XMLHttpRequest object
XMLHttpRequest object that talks to the server. That's not the normal application flow and it's where Ajax gets much of its magic.
In a normal Web application, users fill out form fields and click a Submit button. Then, the entire form is sent to the server, the server passes on processing to a script (usually PHP or Java or maybe a CGI process or something similar), and when the script is done, it sends back a completely new page. That page might be HTML with a new form with some data filled in or it might be a confirmation or perhaps a page with certain options selected based on data entered in the original form. Of course, while the script or program on the server is processing and returning a new form, users have to wait. Their screen will go blank and then be redrawn as data comes back from the server. This is where low interactivity comes into play -- users don't get instant feedback and they certainly don't feel like they're working on a desktop application.
XMLHttpRequest. It can talk back and forth with a server all it wants, without the user ever knowing about what's really going on. The result is a dynamic, responsive, highly-interactive experience like a desktop application, but with all the power of the Internet behind it.
Once you get a handle on
- Change values on the form: It's also simple to update a form, from setting field values to replacing images on the fly.
For those first two items, you want to be very familiar with the
getElementById() method as shown in Listing 2.
There's nothing particularly remarkable here and that's good! You should start to realize that there's nothing tremendously complicated about this. Once you master
With a basic overview under your belt, you're ready to look at a few specifics. Since
XMLHttpRequest is central to Ajax applications -- and probably new to many of you -- I'll start there. As you saw in Listing 1, it should be pretty easy to create this object and use it, right? Wait a minute.
Remember those pesky browser wars from a few years back and how nothing worked the same across browsers? Well, believe it or not, those wars are still going on albeit on a much smaller scale. And, surprise:
XMLHttpRequest is one of the victims of this war. So you'll need to do a few different things to get an
XMLHttpRequest object going. I'll take your through it step by step.
Microsoft's browser, Internet Explorer, uses the MSXML parser for handling XML (you can find out more about MSXML in Resources). So when you write Ajax applications that need to work on Internet Explorer, you need to create the object in a particular way.
XMLHttpRequest on Microsoft browsers.
Listing 3. Create an XMLHttpRequest object on Microsoft browsers
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");.
In a nutshell, this code tries to create the object using one version of MSXML; if that fails, it then creates the object using the other version. Nice, huh? If neither of these work, the
xmlHttp variable is set to false, to tell your code know that something hasn't worked. If that's the case, you've probably got a non-Microsoft browser and need to use different code to do the job.
If Internet Explorer isn't your browser of choice or you write code for non-Microsoft browsers, then you need different code. In fact, this is the really simple line of code you saw back in Listing 1:
var xmlHttp = new XMLHttpRequest object;.
This much simpler line creates an
XMLHttpRequest object in Mozilla, Firefox, Safari, Opera, and pretty much every other non-Microsoft browser that supports Ajax in any form or fashion.
The key is to support all browsers. Who wants to write an application that works just on Internet Explorer or an application that works just on non-Microsoft browsers? Worse yet, do you want to write your application twice? Of course not! So your code combines support for both Internet Explorerand non-Microsoft browsers. Listing 4 shows the code to do just that.
Listing 4. Create an XMLHttpRequest object the multi-browser way
For now, ignore the commenting and weird tags like
XMLHttpRequest. The core of this code breaks down into three steps:
- Create a variable,
xmlHttp, to reference the
XMLHttpRequestobject that you will create.
- Try and create the object in Microsoft browsers:
- Try and create the object using the
- If that fails, try and create the object using the
- Try and create the object using the
xmlHttpstill isn't set up, create the object in a non-Microsoft way.
At the end of this process,
xmlHttp should reference a valid
XMLHttpRequest object, no matter what browser your users run.
So you now understand Ajax and have a basic idea about the
What's the missing piece? How to actually use
XMLHttpRequest. Since this is critical code that you'll use in some form in every Ajax application you write, take a quick tour through what a basic request/response model with Ajax looks like.
You have your shiny new
- Get whatever data you need from the Web form.
- Build the URL to connect to.
- Open a connection to the server.
- Set up a function for the server to run when it's done.
- Send the request.
Listing 5 is a sample of an Ajax method that does these very things, in this order:
Listing 5. Make a request with Ajax
Next, a connection is opened; here's the first place you see
XMLHttpRequest in action again. The method of connection is indicated (GET), as well as the URL to connect to. The final parameter, when set to
true, requests an asynchronous connection (thus making this Ajax). If you used
false, the code would wait around on the server when the request was made and not continue until a response was received. By setting this to
onreadystatechange property of
xmlHttp (remember, that's your instance of the
XMLHttpRequest object) allows you to tell the server what to do when it does finish running (which could be in five minutes or five hours). Since the code isn't going to wait around for the server, you'll need to let the server know what to do so you can respond to it. In this case, a specific method -- called
updatePage() -- will be triggered when the server is finished processing your request.
send() is called with a value of
null. Since you've added the data to send to the server (the city and state) in the request URL, you don't need to send anything in the request. So this fires off your request and the server can do what you asked it to do.
If you don't get anything else out of this, notice how straightforward and simple this is! Other than getting the asynchronous nature of Ajax into your head, this is relatively simple stuff. You'll appreciate how it frees you up to concentrate on cool applications and interfaces rather than complicated HTTP request/response code.
The code in Listing 5 is about as easy as it gets. The data is simple text and can be included as part of the request URL. GET sends the request rather than the more complicated POST. There's no XML or content headers to add, no data to send in the body of the request -- this is Ajax Utopia, in other words.
Have no fear; things will become more complicated as this series progresses. You'll learn how to send POST requests, how to set request headers and content types, how to encode XML in your message, how to add security to your request -- the list is pretty long! Don't worry about the hard stuff for now; get your head around the basics, and you'll soon build up a whole arsenal of Ajax tools.
Now you need to actually deal with the server's response. You really only need to know two things at this point:
- Don't do anything until the
xmlHttp.readyStateproperty is equal to 4.
- The server will stuff it's response into the
The first of these -- ready states -- is going to take up the bulk of the next article; you'll learn more about the stages of an HTTP request than you ever wanted to know. For now, if you simply check for a certain value (4), things will work (and you'll have something to look forward to in the next article). The second item -- using the
xmlHttp.responseText property to get the server's response -- is easy. Listing 6 shows an example of a method that the server can call based on the values sent in Listing 5.
Listing 6. Handle the server's response
Again, this code isn't so difficult or complicated. It waits for the server to call it with the right ready state and then uses the value that the server returns (in this case, the ZIP code for the user-entered city and state) to set the value of another form field. The result is that the
zipCode field suddenly appears with the ZIP code -- but the user never had to click a button!. That's the desktop application feel I talked about earlier. Responsiveness, a dynamic feel, and more, all with a little Ajax code.
Observant readers might notice that the
zipCode field is a normal text field. Once the server returns the ZIP code and the
updatePage() method sets the value of that field with the city/state ZIP code, users can override the value. That's intentional for two reasons: To keep things in the example simple and to show you that sometimes you want users to be able to override what a server says. Keep both in mind; they're important in good user-interface design.
Listing 7. Kick off an Ajax process
If this feels like yet one more piece of fairly routine code, then you're right -- it is! When a user puts in a new value for either the city or state field, the
callServer() method fires off and the Ajax fun begins. Starting to feel like you've got a handle on things? Good; that's the idea!
At this point, you're probably not ready to go out and write your first Ajax application -- at least, not unless you're willing to do some real digging in the Resources section. However, you can start to get the basic idea of how these applications work and a basic understanding of the
If you spend some real time with these issues, you'll be better served than just having some code you can cut-and-paste and throw into an application that you really don't understand. In the next article, you'll put these ideas into practice and I'll give you the details on the code you need to really make applications like this work. So, until then, enjoy the possibilities of Ajax.