So here you are, ready to learn all about this thing called AJAX [1]. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content.
The term AJAX, originally coined by Jesse James Garrett of Adaptive Path in his essay AJAX: A New Approach To Web Applications, is an acronym for "Asynchronous JavaScript [2] And XML [3]." That's a bit of a mouthful, but it's simply describing a technique that uses JavaScript to refresh a page's contents from a web server without having to reload the entire page. This is different from the traditional method of updating web pages, which requires the browser to refresh the entire page in order to display any changes to the content.
Similar techniques have been around in one form or another (often achieved with the help of some clever hacks) for quite a while. But the increasing availability of the XMLHttpRequest class in browsers, the coining of the catchy term AJAX, and the advent of a number of high-profile examples such as Google Maps [4], Gmail [5], Backpack [6], and Flickr [7], have allowed these kinds of highly interactive web applications to begin to gain traction in the development world.
As the term AJAX has become more widespread, its definition has expanded to refer more generally to browser-based applications that behave much more dynamically than old-school web apps. This new crop of AJAX web applications make more extensive use of interaction techniques like edit-in-place text, drag-and-drop, and CSS [8] animations or transitions to effect changes within the user interface. This tutorial will explain those techniques, and show you how to develop AJAX web applications of your own.
This tutorial is an excerpt from my new book, Build Your Own AJAX Web Applications [9]. In the three chapters presented here, we'll discuss the basics of AJAX and learn how it ticks, before delving into the wonderful world of XMLHttpRequest. After we've played around with it, exploring its inner workings, making requests, and updating our application page asynchronously, we begin to develop our first true AJAX application.
It's going to be quite a ride, so I hope you're ready for some adventure! If you'd rather read these chapters offline, download the .pdf version of them [10]. But now, let's get a solid grounding in AJAX.
Chapter 1. AJAX: the Overview
He's escaping, idiot! Dispatch War Rocket Ajax! To bring back his body! -- General Kala, Flash [11] Gordon AJAX Web Applications
AJAX can be a great solution for many web development projects -- it can empower web apps to step up and take over a lot of the ground that previously was occupied almost exclusively by desktop applications.
All the same, it's important to keep in mind that AJAX is not a sort of magic fairy dust that you can sprinkle on your app to make it whizzy and cool. Like any other new development technique, AJAX isn't difficult to mis-use, and the only thing worse than a horrible, stodgy, old-school web app is a horrible, poorly executed AJAX web app.
When you apply it to the right parts of your web application, in the right ways, AJAX can enhance users' experience of your application significantly. AJAX can improve the interactivity and speed of your app, ultimately making that application easier, more fun, and more intuitive to use.
Often, AJAX applications are described as being "like a desktop application in the browser." This is a fairly accurate description -- AJAX web apps are significantly more responsive than traditional, old-fashioned web applications, and they can provide levels of interactivity similar to those of desktop applications.
But an AJAX web app is still a remote application, and behaves differently from a desktop application that has access to local storage. Part of your job as an AJAX developer is to craft applications that feel responsive and easy to use despite the communication that must occur between the app and a distant server. Fortunately, the AJAX toolbox gives you a number of excellent techniques to accomplish exactly that.
The Bad Old Days
One of the first web development tasks that moved beyond serving simple, static HTML [12] pages was the technique of building pages dynamically on the web server using data from a back-end data store.
Back in the "bad old days" of web development, the only way to create this dynamic, database-driven content was to construct the entire page on the server side, using either a CGI script (most likely written in Perl [13]), or some server component that could interpret a scripting language (such as Microsoft's Active Server Pages). Even a single change to that page necessitated a round trip from browser to server -- only then could the new content be presented to the user.
In those days, the normal model for a web application's user interface was a web form that the user would fill out and submit to the server. The server would process the submitted form, and send an entirely new page back to the browser for display as a result. So, for example, the completion of a multi-step, web-based "wizard" would require the user to submit a form -- thereby prompting a round-trip between the browser and the server -- for each step.
Granted, this was a huge advance on static web pages, but it was still a far cry from presenting a true "application" experience to end-users.
Prehistoric AJAX
Early web developers immediately began to look for tricks to extend the capabilities of that simple forms-based model, as they strove to create web applications that were more responsive and interactive. These hacks, while fairly ad hoc and crude, were the first steps web developers took toward the kind of interactivity we see in today's AJAX applications. But, while these tricks and workarounds often provided serviceable, working solutions, the resulting code was not a pretty sight.
Nesting Framesets
One way to get around the problem of having to reload the entire page in order to display even the smallest change to its content was the hideous hack of nesting framesets within other framesets, often several levels deep. This technique allowed developers to update only selected areas of the screen, and even to mimic the behavior of tab-style navigation interfaces in which users' clicking on tabs in one part of the screen changed content in another area.
This technique resulted in horrible, unmaintainable code with profusions of pages that had names like EmployeeEditWizardMiddleLowerRight.asp [14].
The Hidden iframe
The addition of the iframe in browsers like Internet Explorer 4 made things much less painful. The ability to hide the iframe completely led to the development of another neat hack: developers would make HTTP requests to the server using a hidden iframe, then insert the content into the page using JavaScript and DHTML [15]. This provided much of the same functionality that's available through modern AJAX, including the ability to submit data from forms without reloading the page -- a feat that was achieved by having the form submit to the hidden iframe. The result was returned by the server to the iframe, where the page's JavaScript could access it.
The big drawback of this approach (beyond the fact that it was, after all, a hack) was the annoying burden of passing data back and forth between the main document and the document in the iframe.
Remote Scripting
Another early AJAX-like technique, usually referred to as remote scripting, involved setting the src attribute of a <script>tag to load pages that contained dynamically generated JavaScript.
This had the advantage of being much cleaner than the hidden iframe hack, as the JavaScript generated on the server would load right into the main document. However, only simple GET requests were possible using this technique.
What Makes AJAX Cool
This is why AJAX development is such an enormous leap forward for web development: instead of having to send everything to the server in a single, huge mass, then wait for the server to send back a new page for rendering, web developers can communicate with the server in smaller chunks, and selectively update specific areas of the page based on the server's responses to those requests. This is where the word asynchronous in the AJAX acronym originated.
It's probably easiest to understand the idea of an asynchronous system by considering its opposite -- a synchronous system. In a synchronous system, everything occurs in order. If a car race was a synchronous system, it would be a very dull affair. The car that started first on the grid would be the first across the finish line, followed by the car that started second, and so on. There would be no overtaking, and if a car broke down, the traffic behind would be forced to stop and wait while the mechanics made their repairs.
Traditional web apps use a synchronous system: you must wait for the server to send you the first page of a system before you can request the second page.
An asynchronous car race would be a lot more exciting. The car in pole position could be overtaken on the first corner, and the car that starts from the back of the grid could weave its way through the field and cross the finish line in third place. The HTTP requests from the browser in an AJAX application work in exactly this way. It's this ability to make lots of small requests to the server on a needs-basis that makes AJAX development so cool. An AJAX application making asynchronous requests to a web server.
The end result is an application that feels much more responsive, as users spend significantly less time waiting for requests to process, and don't have to wait for an entire new web page to come across the wire, and be rendered by their browsers, before they can view the results.
AJAX Technologies
The technologies that are used to build AJAX web applications encompass a number of different programming domains, so AJAX development is neither as straightforward as regular applications development, nor as easy as old-school web development.
On the other hand, the fact that AJAX development embraces so many different technologies makes it a lot more interesting and fun. Here's a brief listing of the technologies that work together to make an AJAX web application:
- XML
- the W3C DOM
- CSS
- XMLHttpRequest
- JavaScript
Through the rest of this chapter, we'll meet each of these technologies and discuss the roles they play in an AJAX web application.
Data Exchange and Markup: XML
XML(XML stands for Extensible Markup Language -- not that anyone ever calls it that outside of textbooks.) is where AJAX gets its letter "X." This is fortunate, because tech acronyms are automatically seen as being much cooler if they contain the letter "X." (Yes, I am kidding!)
Data Exchange Lingua Franca
XML often serves as the main data format used in the asynchronous HTTP requests that communicate between the browser and the server in an AJAX application. This role plays to XML's strengths as a neutral and fairly simple data exchange format, and also means that it's relatively easy to reuse or reformat content if the need arises.
There are, of course, numerous other ways to format your data for easy exchange between the browser and the server (such as CSV (comma separated values), JSON (JavaScript object notation), or simply plain text), but XML is one of the most common.
XML as Markup
The web pages in AJAX applications consist of XHTML [18] markup, which is actually just a flavor of XML. XHTML, as the successor to HTML, is very similar to it. It's easily picked up by any developer who's familiar with old-school HTML, yet it boasts all the benefits of valid XML. There are numerous advantages to using XHTML:
* It offers lots of standard tools and script libraries for viewing, editing, and validating XML.
* It's forward-compatible with newer, XML-compatible browsers. * It works with either the HTML Document Object Model (DOM) or the XML DOM.* It's more easily repurposed for viewing in non-browser agents.
Some of the more pedantic folks in the development community insist that people should not yet be using XHTML. They believe very strongly that XHTML, since it is actual XML, should not be used at all unless it can be served with a proper HTTP Content-Type header of application/xhtml+xml (text/xml and application/xml would also be okay, though they're less descriptive) for which, at present, there is still limited browser support. (Internet Explorer 6 and 7 do not support it at all.)
In practice, you can serve XHTML to the browser with a Content-Type of text/html, as all the mainstream browsers render correctly all XHTML documents served as text/html. Although browsers will treat your code as plain old HTML, other programs can still interpret it as XML, so there's no practical reason not to "future-proof" your markup by using it.
If you happen to disagree with me, you can choose instead to develop using the older HTML 4.01 standard. This is still a viable web standard, and is a perfectly legitimate choice to make in developing your web application.
XHTML and this Book
Most of the code examples in this book will use XHTML 1.0 Strict. The iframe element is not available in Strict, so the few code examples we show using the iframe will be XHTML 1.0 Transitional.
The World Wide Web Consortium maintains an FAQ on the differences between HTML and XHTML [19].
W3C Document Object Model
The Document Object Model (DOM) is an object-oriented [20] representation of XML and HTML documents, and provides an API for changing the content, structure, and style of those documents.
Originally, specific browsers like Netscape Navigator and Internet Explorer provided differing, proprietary ways to manipulate HTML documents using JavaScript. The DOM arose from efforts by the World Wide Web Consortium (W3C) to provide a platform- and browser-neutral way to achieve the same tasks.
The DOM represents the structure of an XML or HTML document as an object hierarchy, which is ideal for parsing by standard XML tools.
DOM Manipulation Methods
JavaScript provides a large API for dealing with these DOM structures, in terms of both parsing and manipulating the document. This is one of the primary ways to accomplish the smaller, piece-by-piece changes to a web page that we see in an AJAX application. (Another method is simply to change the innerHTMLproperty of an element. This method is not well documented in any standard, though it's widely supported by mainstream browsers.)
DOM Events
The other important function of the DOM is that it provides a standard means for JavaScript to attach events to elements on a web page. This makes possible much richer user interfaces, because it allows you to give users opportunities to interact with the page beyond simple links and form elements.
A great example of this is drag-and-drop functionality, which lets users drag pieces of the page around on the screen, and drop them into place to trigger specific pieces of functionality. This kind of feature used to exist only in desktop applications, but now it works just as well in the browser, thanks to the DOM.
Presentation: CSS
CSS (Cascading Style Sheets) provides a unified method for controlling the appearance of user interface elements in your web application. You can use CSS to change almost any aspect of the way the page looks, from font sizes, colors, and spacing, to the positioning of elements.
In an AJAX application, one very good use of CSS is to provide user-interface [21] feedback (with CSS-driven animations and transitions), or to indicate portions of the page with which the user can interact (with changes to color or appearance triggered, for example, by mouseovers). For example, you can use CSS transitions to indicate that some part of your application is waiting for an HTTP request that's processing on the server.
CSS manipulation figures heavily in the broader definition of the term AJAX -- in various visual transitions and effects, as well as in drag-and-drop and edit-in-place functionality.
Communication: XMLHttpRequest
XMLHttpRequest, a JavaScript class with a very easy-to-use interface, sends and receives HTTP requests and responses to and from web servers. The XMLHttpRequest class is what makes true AJAX application development possible. The HTTP requests made with XMLHttpRequestwork just as if the browser were making normal requests to load a page or submit a form, but without the user ever having to leave the currently loaded web page.
Microsoft first implemented XMLHttpRequest in Internet Explorer 5 for Windows as an ActiveX object. The Mozilla [22] project provided a JavaScript-native version with a compatible API in the Mozilla browser, starting in version 1.0. (It's also available in Firefox [23], of course.) Apple has added XMLHttpRequest to Safari since version 1.2.
The response from the server -- either an XML document or a string of text -- can be passed to JavaScript to use however the developer sees fit -- often to update some piece of the web application's user interface.
Putting it All Together: JavaScript
JavaScript is the glue that holds your AJAX application together. It performs multiple roles in AJAX development:
- controlling HTTP requests that are made using XMLHttpRequest
- parsing the result that comes back from the server, using either DOM manipulation methods, XSLT [24], or custom methods, depending on the data exchange format used
- presenting the resulting data in the user interface, either by using DOM manipulation methods to insert content into the web page, by updating an element's innerHTML property, or by changing elements' CSS properties
Because of its long history of use in lightweight web programming (and at the hands of inexperienced programmers), JavaScript has not been seen by many traditional application developers as a "serious programming language," despite the fact that, in reality, it's a fully-featured, dynamic language capable of supporting object-oriented programming methodologies.
The misperception of JavaScript as a "toy language" is now changing rapidly as AJAX development techniques expand the power and functionality of browser-based applications. As a result of the advent of AJAX, JavaScript now seems to be undergoing something of a renaissance, and the explosive growth in the number of JavaScript toolkits and libraries available for AJAX development is proof of the fact.
Summary
In this chapter, we had a quick overview of AJAX and the technologies that make it tick. We looked at some of the horrible coding contortions that developers had to endure back in the bad old days to create something resembling an interactive UI [25], and we saw how AJAX offers a huge improvement on those approaches. With a decent command of the building blocks of AJAX -- XML, the DOM, CSS, XMLHttpRequest, and JavaScript, which ties them all together -- you have everything you need to start building dynamic and accessible [26] AJAX sites.
Summary
In this chapter, we had a quick overview of AJAX and the technologies that make it tick. We looked at some of the horrible coding contortions that developers had to endure back in the bad old days to create something resembling an interactive UI [25], and we saw how AJAX offers a huge improvement on those approaches. With a decent command of the building blocks of AJAX -- XML, the DOM, CSS, XMLHttpRequest, and JavaScript, which ties them all together -- you have everything you need to start building dynamic and accessible [26] AJAX sites.
About This Article
This article is excerpted from: "Build Your Own Ajax Web Applications" published by Melbourne-based SitePoint.
Order online and get free shipping when you order a second book, plus a bonus video tutorial worth $9.95.