BUY THIS BOOK
Add to Cart

Print Book $49.99


Add to Cart

PDF $39.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £30.99

What is this?

Looking to Reprint or License this content?


Ajax: The Definitive Guide
Ajax: The Definitive Guide

By Anthony T. Holdener III
Book Price: $49.99 USD
£30.99 GBP
PDF Price: $39.99

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Reinventing the Web
Back in 1996, the Web was incredibly exciting, but not a whole lot was actually happening on web pages. Programming a web page in 1996 often meant working with a static page, and maybe a bit of scripting helped manage a form on that page. That scripting usually came in the form of a Perl or C Common Gateway Interface (CGI) script, and it handled basic things such as authorization, page counters, search queries, and advertising. The most dynamic features on the pages were the updating of a counter or time of day, or the changing of an advertising banner when a page reloaded. Applets were briefly the rage for supplying a little chrome to your site, or maybe some animated GIF images to break the monotony of text on the page. Thinking back now, the Web at that time was really a boring place to surf.
But look at what we had to use back then. HTML 2.0 was the standard, with HTML 3.2 right around the corner. You pretty much had to develop for Internet Explorer 3.0 or Netscape Navigator 2.1. You were lucky if someone was browsing with a resolution of 800 × 600, as 640 × 480 was still the norm. It was a challenging time to make anything that felt truly cool or creative.
Since then, tools, standards, hardware technology, and browsers have changed so much that it is difficult to draw a comparison between what the Web was then and what it is today. Ajax's emergence signals the reinvention of the Web, and we should take a look at just how much has changed.
If you want to jump into implementation, skip ahead to . You can always come back to reflect on how we got here.
When a carpenter goes to work every day, he takes all of his work tools: hammer, saw, screwdrivers, tape measure, and more. Those tools, though, are not what makes a house. What makes a house are the materials that go into it: concrete for a foundation; wood and nails for framing; brick, stone, vinyl, or wood for the exterior—you get the idea. When we talk about web tools, we are interested in the materials that make up the web pages, web sites, and web applications, not necessarily the tools that are used to build them. Those discussions are best left for other books that can focus more tightly on individual tools. Here, we want to take a closer look at these web tools (the components or materials, if you will), and see how these components have changed over the history of the Web—especially since the introduction of Ajax.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Web Page Components
When a carpenter goes to work every day, he takes all of his work tools: hammer, saw, screwdrivers, tape measure, and more. Those tools, though, are not what makes a house. What makes a house are the materials that go into it: concrete for a foundation; wood and nails for framing; brick, stone, vinyl, or wood for the exterior—you get the idea. When we talk about web tools, we are interested in the materials that make up the web pages, web sites, and web applications, not necessarily the tools that are used to build them. Those discussions are best left for other books that can focus more tightly on individual tools. Here, we want to take a closer look at these web tools (the components or materials, if you will), and see how these components have changed over the history of the Web—especially since the introduction of Ajax.
The tools of the classic web page are really more like the wood-framed solid or wattle walls of the Neolithic period. They were crude and simple, serving their purpose but leaving much to be desired. They were a renaissance, though. Man no longer lived the lifestyle of a nomad following a herd, and instead built permanent settlements to support hunting and farming. In much the same way, the birth of the Web and these classic web pages was a renaissance, giving people communication tools they never had before.
The tools of the classic Web were few and simple:
  • HyperText Markup Language (HTML)
  • HyperText Transfer Protocol (HTTP)
Eventually, other things went into the building of a web page, such as CGI scripting and possibly even a database.
The World Wide Web Consortium (W3C) introduced the Cascading Style Sheets Level 1 (CSS1) Recommendation in December 1996, but it was not widely adopted for some time after. Most of the available web browsers were slow to adopt the technology. It wasn't until browser makers began to support CSS that it even made sense to start using the technology.
HTML provided everything in a web page in the classic environment. There was no separation of presentation from structure; JavaScript was in its infancy at best, and could not be used to create "dynamic HTML" through Document Object Model (DOM) manipulation, because there was no DOM. If the client and the server were to communicate, they did so using very basic HTTP GET and, sometimes, POST calls.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Modern Web Standards
Web standards: these two words evoke different feelings in different people. Some will scoff and roll their eyes, some will get angry and declare the need for them, and some will get on a soapbox and preach to anyone who will listen. Whatever your view is, it is time to reach a common ground on which everyone can agree. The simple fact is that web standards enable the content of an application to be made available to a much wider range of people and technologies at lower costs and faster development speeds.
Using the standards that have been published on the Web (and making sure they validate) satisfies the following Web Accessibility Initiative-Web Content Accessibility Guidelines (WAI-WCAG) 1.0 guideline:
  • Priority 2 checkpoint 3.2: Create documents that validate to published formal grammars.
In the earlier years of the Web, the browser makers were to blame for difficulties in adopting web standards. Anyone that remembers the days of the 4.0 browsers, more commonly referred to as the "Browser Wars," will attest to the fact that nothing you did in one environment would work the same in another. No one can really blame Netscape and Microsoft for what they did at the time. Competition was stiff, so why would either of them want to agree on common formats for markup, for example?
This is no longer the case. Now developers are to blame for not adopting standards. Some developers are stuck with the mentality of the 1990s, when browser quirks mode, coding hacks, and other tricks were the only things that allowed code to work in all environments. Also at fault is "helpful" What You See Is What You Get (WYSIWYG) software that still generates code geared for 4.0 browsers without any real thought to document structure, web standards, separating structure from presentation, and so forth.
Now several standards bodies provide the formal standards and technical specifications we all love and hold dear to our hearts. For our discussion on standards, we will be concerning ourselves with the W3C (http://www.w3.org/), Ecma International (formerly known as ECMA; http://www.ecma-international.org/
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Browsers
Like standards, browsers can be a touchy subject for some people. Everyone has a particular browser that she is comfortable with, whether because of features, simplicity of use, or familiarity. Developers need to know, however, the differences among the browsers—for example, what standards they support. Also, it should be noted that it's not the browser, but rather the engine driving it that really matters. To generalize our discussion of browsers, therefore, it's easiest to focus on the following engines:
  • Gecko
  • Trident
  • KHTML/WebCore
  • Presto
shows just how well each major browser layout engine supports the standards we have discussed in this chapter, as well as some that we will cover later in the book.
Table : Standards supported by browser engines
Gecko
Trident
KHTML/WebCore
Presto
HTML
Yes
Yes
Yes
Yes
XHTML/XML
Yes
Partial
Partial
Yes
CSS1
Yes
Yes
Yes
Yes
CSS2 (CSS2.1)
Yes
Partial
Yes
Yes
CSS3
Partial
No
Partial
Partial
DOM Level 1
Yes
Partial
Yes
Yes
DOM Level 2
Yes
No
Yes
Yes
DOM Level 3
Partial
No
Partial
Partial
RSS
Yes
No
Yes
Yes
Atom
Yes
No
Yes
Yes
JavaScript
1.7
1.5
1.5
1.5
PNG alpha-transparency
Yes
Yes
Yes
Yes
XSLT
Yes
Yes
No
Yes
SVG
Partial
No
Partial
Partial
XPath
Yes
Yes
No
Yes
Ajax
Yes
Yes
Yes
Yes
Progressive JPEG
Yes
No
Yes
Yes
Gecko is the layout engine built by the Mozilla project and used in all Mozilla-branded browsers and software. Some of these products are Mozilla Firefox, Netscape, and K-Meleon. One of the nice features of Gecko is that it is cross-platform by design, so it runs on several different operating systems, including Windows, Linux, and Mac OS X.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Standards Compliance
So far, I have pointed out the current standards and when they were introduced, as well as which browsers support them, but I still need to answer a burning question: "Why program to standards, anyway?" Let's discuss that now.
What is one of the worst things developers have to account for when programming a site for the Internet? That answer is easy, right? Backward compatibility. Developers are always struggling to make their sites work with all browsers that could potentially view their work. But why bend over backward for the 0.01 percent of people clinging to their beloved 4.0 browsers? Is it really that important to make sure that 100 percent of the people can view your site? Some purists will probably answer "yes," but in this new age of technology, developers should be concerned with a more important objective: forward compatibility.
Forward compatibility is, in all actuality, harder to achieve than backward compatibility. Why? Just think about it for a minute. With backward compatibility, you as a developer already know what format all your data needs to be in to work with older browsers. This is not the case with forward compatibility, because you are being asked to program to an unknown. Here is where standards compliance really comes into play. By adhering to the standards that have been put forth and by keeping faith that the standards bodies will keep backward compatibility in mind when producing newer recommendations, the unknown of forward compatibility is not so unknown. Even if future recommendations do not have built-in backward compatibility, by following the latest standards that have been put forth, you will still, in all likelihood, be set up to make a smoother transition if need be. After all, instead of worrying whether my site works for a browser that is nine years old and obsolete, I would rather worry that my site will work, with only very minor changes, nine years from now. Wouldn't you?
Keep in mind, too, that by complying with the latest standards, you are ensuring that site accessibility can still be achieved. For examples of maintaining accessibility, see "Accessibility" in . After all, shouldn't we be more concerned with making our sites accessible to handicapped viewers than to viewers whose only handicap is that they have not upgraded their browsers?
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Welcome to Web 2.0
So, what exactly do users deserve? They deserve interaction, accessibility, and functionality; but most of all, they deserve for the Web to be a platform, and Ajax is the means to that end. With Ajax, you can make the interface in the browser be just like a desktop application, and it can react faster and offer functionality that web users have not traditionally had in the past (such as inline editing, hints as you type, etc.). Sites can be built that allow unprecedented levels of collaboration. But what, you may ask, is in it for the developers and clients paying for this platform? The answer: lower costs, better accessibility, more visibility, and better perception.
A great plus to building a standards-based Ajax web application is that it is so much easier to maintain. By separating presentation from content, you are allowing your application to be more easily modified and updated. It also reduces the size of files, consuming less bandwidth. This equals less money spent on making those changes and lower hosting costs for your application. Another plus is that your web application becomes more accessible to your viewers. A well-built web application functions in a manner in which users have come to expect from desktop applications, and can more easily adapt to your site. Also, the accessibility for handicapped viewers is more readily available (we will discuss the coding for such sites in later chapters). Search engines can more easily interpret the relevance of text on your site when the application is coded correctly. This leads to better visibility on these search engines, and more viewing of your application, as you are better represented by user queries. Finally, users will have a better perception of your application when it provides easy-to-use navigation, reacts quickly, and functions correctly in their browsers. And who can perceive a site badly when it loads quickly, yielding better user experiences?
Ajax web development gives you everything you need. And what makes Ajax special is that it is not a new technology—it is the combination of many technologies that have been around for a while and that are production-tested. User interaction, fast response time, desktop-like features: web applications are no longer something that you can only dream of for the future. Web applications are in the here and now. Welcome to Web 2.0 with Ajax.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: From Web Sites to Web Applications
Ajax web applications are here, and they are the future of the Web. The big question at this point is, how do we get there? How do we get from simple web sites to web applications? This seems easy on the surface, right?
Unfortunately, it's not easy. Developing an application, whether it is on the desktop or on the Web, takes more forethought than the old model of web design did. Think for a minute about the old model. Sure, you could lay out your site and know what pages you wanted linked to other pages, or maybe you could draw a simple flow diagram, but that was usually as far as it went. Need to add another page? No problem: you'd create it and stick the link for it wherever it needed to be.
There is nothing wrong with this process, especially for small sites. Web sites in general are not inherently complicated, and they don't need a more complex development model (though content management can be helpful). Application development, for the Web or otherwise, demands a more structured approach, however.
If you want to jump into implementation, skip ahead to . You can always come back to reflect on best practices for development.
The art of computer science slowly begins to creep back into the Web as the application life cycle begins. Any software developer can describe the life cycle of a software application. If a programmer does not learn it as part of her curriculum in school, you can bet she finds out what it is very quickly on the job. Why is this so important? Because it is a process that is tried and true (though not necessarily followed consistently). shows a typical life cycle model.
Figure : The typical software development life cycle
Following are the phases of software application development.
Requirements analysis
Gathering the customer's requirements and figuring out the appropriate way to proceed with each item. This phase usually produces a formal requirements document aimed at freezing all of the requirements so that the design phase may begin.
Design
Designing the software based on the requirements document. Programmers lay out classes and their members and methods, and might create UML diagrams for documentation. This phase produces a formal design document that the developers will use as a reference when they implement the design.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Transition
The art of computer science slowly begins to creep back into the Web as the application life cycle begins. Any software developer can describe the life cycle of a software application. If a programmer does not learn it as part of her curriculum in school, you can bet she finds out what it is very quickly on the job. Why is this so important? Because it is a process that is tried and true (though not necessarily followed consistently). shows a typical life cycle model.
Figure : The typical software development life cycle
Following are the phases of software application development.
Requirements analysis
Gathering the customer's requirements and figuring out the appropriate way to proceed with each item. This phase usually produces a formal requirements document aimed at freezing all of the requirements so that the design phase may begin.
Design
Designing the software based on the requirements document. Programmers lay out classes and their members and methods, and might create UML diagrams for documentation. This phase produces a formal design document that the developers will use as a reference when they implement the design.
Implementation
The actual coding of the software. What is produced here is a working version of the software, maybe along with a user manual or some other software documentation.
Testing
Putting the software through a validation and verification process against the requirements document produced in the requirements analysis phase.
Release
Packaging the software in a manner suitable for distribution to the public.
Maintenance
Fixing any new bugs that may be discovered once the software has been released, and producing patches.
Upgrade
Identifying a need for the software to be enhanced or upgraded in some manner. At this point, the life cycle process starts over.
This life cycle works, but it may be a little formal for most Ajax web development. shows a simpler Ajax web application life cycle.
Figure : The Ajax web application development life cycle
Why simplify the process for the Web? A lot of applications on the Web are the product of a more rapid development process, and simplifying the model makes it easier to keep that quick pace. An Ajax application can also follow the traditional development life cycle, but the simpler cycle fits better with the rapid iteration development style often used for web work.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Basic Web and Ajax Design Patterns
Design patterns! Now, before anyone gets too excited, this isn't going to be another book that talks about the general subject of design patterns. Erich Gamma et al. did a fine job of that in the book Design Patterns (Addison-Wesley). There is a time and place for further discussions, and this isn't it. Instead, I want to take a look at the development of the overall design pattern that defines an Ajax web application.
The simplest definition of a design pattern is "the solution to a problem in generic terms." I want to keep the discussion of an Ajax design pattern to that. Check out Ajax Design Patterns, by Michael Mahemoff (O'Reilly), for a vastly more detailed look at design patterns as they relate to specific Ajax problems and their solutions.
To begin our discussion of design patterns, we'll study the classic model of an Internet site and see how it evolved into the design pattern used today in Ajax web applications.
When web sites were first being built and all of the content was static, the Web as a whole was built on client/server architecture. This architecture is basically predicated on the thought that many clients (web browsers in this case) connect to servers that host web pages, as shown in . With this environment, the client is active, sending requests and waiting for replies from a server that is passive, waiting for requests and sending them when asked for.
Figure : The client/server model for the Web
This basic pattern was all that the Web needed until the introduction of forms and server-side scripting. This allowed servers to begin to deliver and process more dynamic data. Eventually, the use of simple databases entered the scene, and the design pattern of the Web changed.
With the introduction of databases and database servers to the architecture, the Web became a three-tier design pattern, as shown in . Now, the client made a request to the server, which processed that request and could, in turn, request data from the database server.
Figure : The basic three-tier model for the Web
This design pattern evolved over time as server scripting became more robust, and more could be done with browsers. The software architecture design pattern slowly crept into the picture, and instead of viewing the architecture in terms of clients and servers, it viewed the architecture in a more abstract manner.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Application Environments
You can implement Ajax web applications in many environments. Each of them has special design considerations. Understanding the environment for which the application is to be built is as important as understanding for whom the application is to be built.
A lot of Ajax web applications the public will never see, because they are meant for company intranets. Intranets, unfortunately, come in different shapes and sizes, so to speak, and there is never a one-size-fits-all approach to them.
The first consideration for an intranet application is the browser environment in which you will be working. More often than not, a large corporation has standards dictating that all applications must be built for a certain browser. This makes your job easier. Smaller environments, which do not have such standards, are harder to develop for. Your goal should be to attempt to develop toward one browser, to reduce incompatibility issues, code size, and code complexity.
Speaking of company standards, the operating system that the client browser sits on is also an important consideration. Most large companies will have one operating system for all desktop applications to work in, and this is usually some flavor of Windows. A smaller company is more likely or willing to try an alternative to Windows that costs less money. This is an important consideration. If you intend for your Ajax web application to utilize a plug-in, you need to know whether the plug-in is supported in the operating system environment you are programming against.
Let's not forget about existing applications. Companies may want your Ajax web application to integrate with an existing web site, or maybe even a desktop application. It is much less confusing for the end user if things appear to work seamlessly together.
A commercial Ajax web application is most likely the hardest environment in which to program. Why is this? Because in these situations, you must make absolutely sure that your application can function everywhere. It must work on every modern commercial browser, and it must work on every operating system. After all, this is why Ajax web applications are getting so much notice in the first place. Unlike desktop applications, it takes less code, programming, and money to roll out a commercial Ajax application.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Developer
At this point, you've had a little primer on Ajax web development life cycles, the basic design pattern of Ajax applications, and considerations for different environments in which your application could be used. What else do you need to know to move from building web sites to building web applications? An important bit of information to hold on to is that a web application is just that: an application. It is more complex to build, it takes more time, and it requires more skilled developers to build it right. It isn't as simple as opening a text browser, writing some markup, and saving it with an .html extension.
A web application developer has to know XHTML, CSS, JavaScript, XML, and the Document Object Model (DOM) at a minimum. Most developers also know Extensible Stylesheet Language Transformation (XSLT), and syndication techniques. And remember, this is just the client side of things. In , we will explore the other side of Ajax, which is the server side. A developer should also understand how the HTTP server works, one or more server-side scripting languages, and databases. Web applications require developers to know a wider variety of things than a desktop application developer would ever need to know. If people were mystified by how web sites worked before, what will they think about Ajax web applications now?
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What Ajax Is Not
Ajax is not the be-all and end-all solution to every new application being built for the Web. It is not even something that should be considered as an upgrade to every existing product. Ajax is a great model for building more modern, faster Web 2.0 applications, but only when they are built correctly. Throwing Ajax at every application can create complications, such as accessibility issues, cross-browser compliance nightmares, and requiring more intricate and complex programming to perform simple tasks.
I want to make sure this is clear, before everyone gets all gung-ho and throws Ajax everywhere. Ajax is not for everything. Let me repeat that. Ajax is not for everything. Take a look at for risks that Ajax can create.
I love the Ajax model of design; I think it brings web applications closer to the capabilities of desktop applications. I also know, somewhat from experience, that Ajax is not the best solution for every project, and that it can sometimes overcomplicate what could have been a simple solution. As you read the rest of this book and you see Ajax solutions that I present to common web design issues, ask yourself whether Ajax is right for you and what you are trying to accomplish. It could fit perfectly, but it could also be the wrong solution for you after all.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Servers, Databases, and the Web
Most of this book will be about the client side, as people think of Ajax as something that works specifically in the browser. Ajax definitely needs server support to work, though. So far, we've looked at the standards and technology that form the backbone of an Ajax web application, and how these applications moved away from the traditional web site model. Now, it's time to turn our attention to the server side of things.
Servers still hand out all of the requested data to the client, so we cannot always focus on the client side. It is important to understand the different web servers, server-side scripting languages, and databases that are available to developers. How will you know which of these to choose? Well, the old saying "there is a place for everything, and everything has its place" has real merit here.
I cannot tell you which web server is better, or what language you should use, or which database is the best. Those are choices each developer must make. To make that process a little easier, I will provide information on all of these choices and how they relate to Ajax web applications, with the hope that you will be able to back up with hard facts whatever choice you make.
The fact is (and this is a good thing, really) that unlike on the client side, where you have to use XHTML or HTML, CSS, JavaScript, the Document Object Model (DOM), and so forth with no choice in the matter, on the server side you have many good choices to explore and vastly more opportunities to work with the tools you like and to avoid the ones that seem inconvenient.
If you want to jump into client-side implementation, skip ahead to . You can always return to the server side of the conversation.
Only two servers are widely used on the Web today: the Apache HTTP Server from the Apache Software Foundation (http://httpd.apache.org/) and Internet Information Services (IIS) from Microsoft (http://www.iis.net/). At the most rudimentary level, both of these HTTP servers function in the same basic way, as shown in . A client browser requests information from the server in the form of an HTTP request. The server responds to the request by sending an appropriate response, usually in the form of an XHTML document, an image, a raw text file, or some other type of document. If the request is bad, the server's response is in the form of an error.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Web Server
Only two servers are widely used on the Web today: the Apache HTTP Server from the Apache Software Foundation (http://httpd.apache.org/) and Internet Information Services (IIS) from Microsoft (http://www.iis.net/). At the most rudimentary level, both of these HTTP servers function in the same basic way, as shown in . A client browser requests information from the server in the form of an HTTP request. The server responds to the request by sending an appropriate response, usually in the form of an XHTML document, an image, a raw text file, or some other type of document. If the request is bad, the server's response is in the form of an error.
Figure : The typical model for an HTTP server
According to the October 2007 Netcraft Web Server Survey (http://news.netcraft.com/archives/2007/10/11/october_2007_web_server_survey.html), Apache had a 47.73 percent market share, whereas Microsoft had 37.13 percent (this is a combination of all servers using Personal Web Server, both PWS and PWS-95, and IIS, both IIS and IIS-W). This doesn't automatically mean that Apache is better than IIS. For one thing, Apache has been around longer than IIS, giving Apache an edge since it's already been integrated into a lot of systems. For another, Apache is open source software, and it is free. IIS only comes prebundled with the server versions of Windows and cannot be downloaded separately. Finally, Apache runs on pretty much every operating system out there—Windows, Mac OS X, and all flavors of Linux and Unix. IIS runs only on Windows.
But what is really important when it comes to comparing different software applications is looking at their features. examines the features available with Apache and IIS.
Table : Web server features
Basic authentication
https
Virtual hosting
CGI
FastCGI
Servlet
SSI
Apache HTTP Server
Yes
Yes
Yes
Yes
Yes
Yes
Yes
IIS
Yes
Yes
Yes
Yes
No
No
Yes
Now, although security features such as authentication and https are important for a web server, because the topic is Ajax web applications our focus should be on what the web server can do for dynamic interaction. This is where CGI, FastCGI, servlets, and SSI come into play. All provide ways for the HTTP server to provide dynamic content back to the client.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Server-Side Scripting
Server-side scripting in the early days of web development was done with C, Pascal, or Perl for a CGI script. In the cases of C and Pascal, this was not even really scripting in the traditional sense, as these CGI "scripts" were compiled programs. They did what developers needed them to do: crank out dynamic content quickly. In fact, many CGI programs are still written in C, and they work faster and better than any true scripting language. MapServer (http://mapserver.gis.umn.edu/) is a good example of one of these.
Scripting languages hold one distinct advantage over their compiled brethren: they have better portability. Think about a compiled language on a Windows system, or a Linux system, for that matter. If I wrote a program for Windows 2000, I relied on the DLLs for that operating system when I compiled my program. If I want to port that program to Windows Vista, I may have to do a lot of work to make sure all of the DLLs are compatible on the new system. Worse still, I may need to modify my code for it to compile correctly on the new system. This is true for the *NIXs as well. They all have libraries that are not compatible with one another, making portability a chore.
With scripting languages, on the other hand, once the interpreter for the language in question has been ported to the operating system I want to port to, the script will move to the new system without needing any modifications. That is the beauty of scripting languages, and it's why they are used so heavily in the Web 2.0 environment.
Before we go any further, I want to point out that of the languages I will be detailing next, I do not believe any particular one is better than another. They all have their pros and cons. I am not saying I do not have a favorite; I do. I am just not going to say, "You have to pick X because it is the best."
Microsoft introduced ASP in December 1996 with the distribution of IIS 3.0, and it was Microsoft's solution for dynamic content for the Web. ASP uses the idea of built-in objects to allow for easier web site construction, for common needs such as Response, Request, and Session, among others. The most common scripting language used for ASP is Microsoft's VBScript, though other languages could be used as well (JScript comes to mind). Since ASP is an SSI interpreted technology, it uses delimiters to separate scripting code from straight markup, as shown here:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Databases
Databases allow web applications to store information in a systematic way, and retrieve that information later through the use of a structured query. Before database use became popular on the Web, plain text files were used to store this information. This was slower, not because of read and write access to the files, but because it was difficult to query information contained in the files in a timely manner. Besides being faster for querying, databases also allow many clients to access and save information concurrently. This is very important in the case of web applications, as there is always the potential for hundreds of people to be accessing the application at any one time.
Databases are becoming more sophisticated over time, and they are now meeting the demands of the Internet like never before. As they begin to natively support XML, they will increase the speed of Ajax web applications even more than they do today. This is good news, because these web applications are not going to go away, and data storage needs will become greater and greater.
Oracle has been around for a long time. In 1979, Relational Software, Inc. (RSI) introduced a relational database system called Oracle V2. The product has changed a lot since then, having been rewritten in C and having added a host of enhancements, including transactions, stored procedures and triggers, support for PL/SQL, a native JVM, XML capabilities, cluster support, and grid computing. The current version of Oracle is 10gR2.
Oracle (http://www.oracle.com/) is known for its stability and reliability under a heavy workload, and it is deployed often in data warehousing environments because of this. In 1999, Oracle became more Internet-ready, with Oracle 8i, and has since added more enhancements to meet the Internet's increasing use as a platform. Oracle also is very scalable, having multiple editions to support a wide range of requirements.
The major issue with using Oracle on the Web is its inherently high price, with Oracle's Enterprise Edition costing in the tens of thousands of dollars per processor. This is a deterrent for companies looking for cheaper solutions to their database-driven Internet applications. Despite the high costs, though, Oracle leads the commercial database market.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Getting Data Into and Out of Relational Databases
Ajax is about programming on the client and on the server, as I have already discussed. Though this book focuses primarily on the client end of an Ajax application, it still includes some server-side scripting examples. Part of that is interfacing with the database. For good or for bad, as an Ajax developer you must understand at least the basics of database development, unless you are lucky enough to have a database administrator on the project that can do this stuff for you. Even then, it is a good idea to understand how databases can work for you.
Because most web applications are built using relational databases, this section focuses on working with that common model. There isn't room in this book to provide a full tutorial, but if you haven't worked with relational databases before, this section should at least give you some idea of what they do and how they might store data for your applications.
The first thing a developer needs to learn when developing a database is how to create tables. More than that, a developer must learn how to build tables efficiently and in a relational manner. For the following examples, let's assume that we have been tasked with developing a database based on tabular data that had been kept in a spreadsheet containing a list of books in a personal collection.
The spreadsheet includes the following columns:
  • Title of the Book
  • Author(s) of the Book
  • Publishing Date
  • Publisher
  • ISBN-10
  • ISBN-13
  • Number of Pages
  • Original Price of Book
  • Type of Book
  • Category of Book
  • Bought New/Used or Gift
That should be enough to get us started. Obviously, if this were a real-world application, we would have a much more comprehensive list of columns to work from.
I have always found it easiest to look at a data set and determine what can be separated into look-up and cross-reference tables before tackling the main tables—you may find a different method easier. Looking at the columns in the spreadsheet, it immediately becomes clear to me that I can create several columns as look-up tables, mainly the Type of Book, Category of Book, and Bought New/Used or Gift columns. Let's look at how we can create these tables in a MySQL database.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Interfacing the Interface
Covering all of the tools available on the backend of an Ajax application is one thing, but showing how they interact with a client is another. Server-side scripting has changed, not so much in how the developer codes with the language, but in what the client needs or expects to get back from the server. Take, for instance, , which shows the typical server response from a client submitting a form.
Example . A typical server response to a form submit
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html401/loose.dtd">
<HTML>
    <HEAD>
        <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
        <TITLE>Example 3-1. A typical server response to a form submit.</TITLE>
    </HEAD>
    <BODY BGCOLOR="WHITE">
        <H1>Query Results</H1>
            <TABLE>
                <TR><TH>Book Name</TH></TR>
<?php
require('db.inc');
if (!($conn = @mysql_connect($host, $username, $password)))
    die('Could not connect to the database.');
$author = mysql_real_escape_string(isset($_POST['authorName']) ?
    $_POST['authorName'] : '');
if (!@mysql_select_db($db, $conn))
    die('Could not select database.');
$sql = 'SELECT book_id, book_nm FROM books, authors WHERE books.author_id '
    .'= authors.author_id';
if (isset($author))
    $sql .= " AND authors.author_nm = $author'";
$sql .= ' ORDER BY book_nm';
if ($result = @mysql_query($sql, $conn)) {
    while ($row = @mysql_fetch_assoc($result)) {
?>
            <TR><TD><?= $row['book_nm']; ?></TD></TR>
<?php
    }
    mysql_free_result($result);
    mysql_close($conn);
} else {
?>
            <TR><TD>There were no results for the specified query.</TD></TR>
<?php
}
?>
        </TABLE>
    </BODY>
</HTML>
First, note how this example uses PHP as the server-side scripting language and MySQL as the database. This book's examples will generally follow this design, not because I believe these are better than the other languages and databases I've outlined, but simply because I find them easy to use, especially for demonstration purposes. In this example, the server processes the data posted to it and then creates a response in the form of a full HTML document. What makes this bad in an Ajax application sense is that the browser must load all of the content for the page again. If images, CSS, and JavaScript were included in this file, they would all have to be downloaded again as well. This is why the classic style of building web pages is not ideal for application building. Compare this with , which shows how a typical Ajax response would be generated.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Frameworks and Languages
Frameworks have been getting a lot of press lately, as those such as Ruby on Rails have gained the notice of more and more professionals in the industry. The truth is, however, that frameworks have been around for a while—longer with some languages than others. But what exactly is a framework? In the simplest terms, a framework is a set of components (interfaces and objects) that are put together to solve a particular problem.
Frameworks are built to ease the burden of writing all of the low-level coding details that go along with programming an application. An important feature of frameworks is that they should work on a generic level so that they are suited for a multitude of applications. On the Web and the desktop, frameworks allow developers to concentrate on the application's requirements and on meeting deadlines, instead of on the mundane but necessary components that make applications run.
With our focus on Ajax web development, it is important to understand the differences among the various frameworks on the Web, not just within a given language, but among languages as well. Earlier in the chapter, we focused on ASP/ASP.NET, PHP, Python, Ruby, and Java, so the frameworks we discuss here will correspond with these languages. Some of these frameworks follow the Model-View-Controller (MVC) design pattern discussed in , and others are just a whole lot of functionality bundled together. Your choice of framework will depend on how structured you want to be.
The Microsoft .NET Framework (http://msdn.microsoft.com/netframework/) is positioned to be the development platform for all new Windows applications, on the Web as well as the desktop. Because of this strategy, it is built as part of the Windows operating system and not as a separate component, as all other frameworks are. And although Microsoft was specifically looking at its flagship Windows operating systems when it designed the .NET Framework, it built the framework to theoretically be a portable language.
As we discussed in the section "ASP/ASP.NET," earlier in this chapter, instead of .NET languages being compiled into machine-level instructions, they are first compiled into a common bytecode and then into a DLL. That is a high-level description of the architecture, but we should delve into it further, and does just that.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What Good Are Frameworks?
The title of this section speaks for itself. I have described some of the frameworks that are available for different scripting languages, but just what good are they? Are they more than just a popular buzzword that has been floating around? The answer, in a word, is yes!
Frameworks are designed to solve recurring problems in application development. So, instead of just trying to explain their usefulness, I will show you.
One of the problems developers face with any web application is providing dynamic data to the client. This is solved by the interaction of the server-scripting language with a database of some kind. Let's take another look at :
<?php
/**
 * Revisiting Example 3-2.
 */

/**
 * The generic db.php library, containing database connection information such as
 * username, password, server, etc., is required for this example.
 */
require('db.inc');

/* Output the XML Prolog so the client can recognize this as XML */
$xml = <<< PROLOG
<?xml version="1.0" encoding="iso-8859-1"?>
PROLOG;

/* Is there a connection to the database server? */
if (!($conn = @mysql_connect($host, $username, $password)))
    $xml .= '<error>Could not connect to the database.</error>';

$author = mysql_real_escape_string(isset($_POST['authorName']) ?
    $_POST['authorName'] : '');

/* Could the database be selected? */
if (!@mysql_select_db($db, $conn))
    $xml .= '<error>Could not select database.</error>';

$sql = 'SELECT book_id, book_nm FROM books, authors WHERE books.author_id '
      .'= authors.author_id';
/* Was the parameter /authorName/ passed to this script? */
if (isset($author))
    $sql .= " AND authors.author_nm = '$author'";
$sql .= ' ORDER BY book_nm';

/* Are there results from the query? */
if ($result = @mysql_query($sql, $conn)) {
    $xml .= '<results>';
    /* Loop through the records
    while ($row = @mysql_fetch_assoc($result))
        $xml .= "<result>{$row['book_nm']}</result>";
    /* Were there any records to loop through? */
    if (!@mysql_num_rows($result))
        $xml .= '<result>There were no results for the specified query.</result>';
    $xml .= '</results>';
    /* Free the mysql result */
    mysql_free_result($result);
    mysql_close($conn);
} else
    $xml .= '<results>'
           .'<result>There were no results for the specified query.</result>'
           .'</results>';

/*
 * Change the header to text/xml so that the client can use the return
 * string as XML
 */
header("Content-Type: text/xml");
echo $xml;
?>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Foundations: Scripting XML and JSON
It's time to switch gears and look at code for Ajax web applications. The most important part of an Ajax application is the connection between the client and the server. If this code is not solid and optimized, your application could suffer sluggish (or simply broken) behavior as a result.
You code the connection between the client and the server using JavaScript, and usually build the data format used to exchange information in XML. I say usually because a new format is on the rise and is fast becoming the new choice for web developers. This new format is JavaScript Object Notation (JSON).
In this chapter, we will explore how to use XML and JSON to transmit data. We will also discuss how the client and the server can parse or otherwise manipulate these formats. Of course, a discussion of this nature would be incomplete without some points on the differences among browser versions, and how to make cross-browser-compatible code.
We will start with XML, as it is part of the original meaning of Ajax. This section will cover the basics of how Ajax works and what to do with the XML that is sent back and forth between the client and the server. First, driving the Ajax component of an Ajax web application is the XMLHttpRequest object. This object allows for asynchronous communication between the client and the server. In other words, the client can start communicating with the server, and instead of the client freezing up and becoming unusable until that communication is complete, the client can continue to function like normal.
Unfortunately for the developer, how an XMLHttpRequest object is implemented is different from one browser to the next. For Safari, Mozilla, Opera, and other like-minded browsers, you create the object like this:
var request = new XMLHttpRequest( );
For browsers that use ActiveX controls, you simply pass the name of the object to the ActiveX control:
var request = new ActiveXObject('Microsoft.XMLHTTP');
Once the object has been instantiated, whether you are using the XMLHttpRequest object or the ActiveX version, the object has the same basic methods and properties associated with it, as shown in and .
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
XML
We will start with XML, as it is part of the original meaning of Ajax. This section will cover the basics of how Ajax works and what to do with the XML that is sent back and forth between the client and the server. First, driving the Ajax component of an Ajax web application is the XMLHttpRequest object. This object allows for asynchronous communication between the client and the server. In other words, the client can start communicating with the server, and instead of the client freezing up and becoming unusable until that communication is complete, the client can continue to function like normal.
Unfortunately for the developer, how an XMLHttpRequest object is implemented is different from one browser to the next. For Safari, Mozilla, Opera, and other like-minded browsers, you create the object like this:
var request = new XMLHttpRequest( );
For browsers that use ActiveX controls, you simply pass the name of the object to the ActiveX control:
var request = new ActiveXObject('Microsoft.XMLHTTP');
Once the object has been instantiated, whether you are using the XMLHttpRequest object or the ActiveX version, the object has the same basic methods and properties associated with it, as shown in and .
Table : The XMLHttpRequest object's properties
Property
Description
onreadystatechange
The function assigned to this property, which is an event listener, is called whenever the readyState of the object changes.
readyState
This property represents the current state that the object is in. It is an integer that takes one of the following:
  • 0 = uninitialized (The open( ) method of the object has not been called yet.)
  • 1 = loading (The send( ) method of the object has not been called yet.)
  • 2 = loaded (The send( ) method has been called, and header and status information is available.)
  • 3 = interactive (The responseText<