Ajax And Php Building Responsive Web Applications 1st Edition Bogdan Brinzarea Cristian Darie Filip Cherechestosa Mihai Bucica

ikwukarels85 6 views 75 slides May 19, 2025
Slide 1
Slide 1 of 75
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75

About This Presentation

Ajax And Php Building Responsive Web Applications 1st Edition Bogdan Brinzarea Cristian Darie Filip Cherechestosa Mihai Bucica
Ajax And Php Building Responsive Web Applications 1st Edition Bogdan Brinzarea Cristian Darie Filip Cherechestosa Mihai Bucica
Ajax And Php Building Responsive Web Applicati...


Slide Content

Ajax And Php Building Responsive Web
Applications 1st Edition Bogdan Brinzarea
Cristian Darie Filip Cherechestosa Mihai Bucica
download
https://ebookbell.com/product/ajax-and-php-building-responsive-
web-applications-1st-edition-bogdan-brinzarea-cristian-darie-
filip-cherechestosa-mihai-bucica-22009510
Explore and download more ebooks at ebookbell.com

AJAX and PHP
Building Responsive Web Applications



Enhance the user experience of your PHP website
using AJAX with this practical tutorial featuring detailed
case studies



Cristian Darie
Bogdan Brinzarea
Filip Cherecheş -Toşa
Mihai Bucica





BIRMINGHAM - MUMBAI

AJAX and PHP
Building Responsive Web Applications
Copyright © 2006 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, without the prior written permission of the publisher,
except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without warranty,
either express or implied. Neither the authors, Packt Publishing, nor its dealers or distributors will
be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all the companies and
products mentioned in this book by the appropriate use of capitals. However, Packt Publishing
cannot guarantee the accuracy of this information.

First published: March 2006

Production Reference: 1210206

Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 1-904811-82-5
www.packtpub.com
Cover Design by www.visionwt.com

Credits
Authors
Cristian Darie
Brinzarea Bogdan
Filip Cherecheş-Toşa
Mihai Bucica

Reviewers
Emilian Balanescu
Paula Badascu

Technical Editor
Jimmy Karumalil

Editorial Manager
Dipali Chittar

Development Editor
Cristian Darie

Indexer
Ashutosh Pande

Proofreader
Chris Smith

Production Coordinator
Manjiri Nadkarni

Cover Designer
Helen Wood

About the Authors
Cristian Darie is a software engineer with experience in a wide range of modern technologies,
and the author of numerous technical books, including the popular "Beginning E-Commerce"
series. Having worked with computers since he was old enough to press the keyboard, he initially
tasted programming success with a first prize in his first programming contest at the age of 12.
From there, Cristian moved on to many other similar achievements, and now he is studying
distributed application architectures for his PhD degree. He always loves hearing feedback about
his books, so don't hesitate dropping a "hello" message when you have a spare moment. Cristian
can be contacted through his personal website at
www.cristiandarie.ro.
Cristian would like to express a big "thank you!" to his co-authors, Bogdan, Filip, and Mihai
and to the Technical Editor of the book, Jimmy, for the hard work they've put into building
this wonderful book.

Bogdan Brinzarea has a strong background in Computer Science holding a Master and
Bachelor Degree at the Automatic Control and Computers Faculty of the Politehnica University of
Bucharest, Romania and also an Auditor diploma at the Computer Science department at Ecole
Polytechnique, Paris, France.
His main interests cover a wide area from embedded programming, distributed and mobile computing, and new web technologies. Currently, he is employed as an Alternative Channels
Specialist at Banca Romaneasca, Member of National Bank of Greece, where he is responsible for
the Internet Banking project and coordinates other projects related to security applications and
new technologies to be implemented in the banking area.

Filip Cherecheş-Toşa is a web developer with a firm belief in the future of web-based software.
He started his career at the age of 9, when he first got a Commodore 64 with tape-drive.
Back home in Romania, Filip runs a web development company named eXigo www.exigo.ro,
which is actively involved in web-based application development and web design. He is currently
a student at the University of Oradea, studying Computer Science, and also an active member of
the Romanian PHP Community www.phpromania.net.

Mihai Bucica started programming and competing in programming contests (winning many
of them), all at age twelve. With a bachelor's degree in computer science from the Automatic
Control and Computers Faculty of the Politehnica University of Bucharest, Romania, Bucica
works on building communication software with various electronic markets.
Even after working with a multitude of languages and technologies, Bucica's programming
language of choice remains C++, and he loves the LGPL word. Mihai also co-authored Beginning
PHP 5 and MySQL E-Commerce and he can be contacted through his personal website,
www.valentinbucica.ro.

About the Reviewers
Emilian Balanescu is a programmer experienced in many technologies, including PHP, Java,
.NET, PostgreSQL, MS SQL Server, MySQL, and others. He currently works as a Wireless
Network Administrator at accessNET International S.A. Romania, a company that provides fixed
wireless access services operating a point-to-multipoint digital radio communication network with
national coverage. His latest project in this position was developing an AJAX-enabled real-time
Network Management System (using SNMP, Perl, PHP, and PostgreSQL) used for remote
debugging, monitoring system performance, and isolating and troubleshooting system problems.
You can reach Emilian at
http://www.emilianbalanescu.ro .

Paula Badascu is in the third year of studies at Politehnica University of Bucharest, one of the
most famous technical universities in Romania, studying Electronics, Telecommunications, and
Information Technology. Paula is currently working as an analyst/programmer for NCH Advisors
Romania, building web applications using UML, OOP, PHP, SQL, JavaScript, and CSS. She
contributed decisively to the analysis and development of a framework used for tracking and
monitoring the Romanian capital market.

Table of Contents
Preface 1
Chapter 1: AJAX and the Future of Web Applications 7
Delivering Functionality via the Web 8
Advantages of Web Applications 9
Building Websites Since 1990 10
HTTP and HTML 10
PHP and Other Server-Side Technologies 11
JavaScript and Other Client-Side Technologies 12
What's Been Missing? 13
Understanding AJAX 14
Building a Simple Application with AJAX and PHP 18
Time for Action—Quickstart AJAX 21
Summary 28
Chapter 2: Client-Side Techniques with Smarter JavaScript 29
JavaScript and the Document Object Model 30
Time for Action—Playing with JavaScript and the DOM 32
JavaScript Events and the DOM 33
Time for Action—Using JavaScript Events and the DOM 35
Even More DOM 37
Time for Action—Even More DOM 37
JavaScript, DOM, and CSS 39
Time for Action—Working with CSS and JavaScript 39
Using the XMLHttpRequest Object 42
Creating the XMLHttpRequest Object 43
Creating Better Objects for Internet Explorer 45
Initiating Server Requests Using XMLHttpRequest 46
Handling Server Response 49
Time for Action—Making Asynchronous Calls with XMLHttpRequest 50

Table of Contents
Working with XML Structures 55
Time for Action—Making Asynchronous Calls with XMLHttpRequest and XML 55
Handling More Errors and Throwing Exceptions 59
Creating XML Structures 63
Summary 64
Chapter 3: Server-Side Techniques with PHP and MySQL 65
PHP and DOM 65
Time for Action—Doing AJAX with PHP 66
Passing Parameters and Handling PHP Errors 71
Time for Action—Passing PHP Parameters and Error Handling 72
Connecting to Remote Servers and JavaScript Security 79
Time for Action—Connecting to Remote Servers 81
Using a Proxy Server Script 85
Time for Action—Using a Proxy Server Script to Access Remote Servers 86
A Framework for Making Repetitive Asynchronous Requests 91
Time for Action—Implementing Repetitive Tasks 93
Working with MySQL 101
Creating Database Tables 101
Manipulating Data 104
Connecting to Your Database and Executing Queries 105
Time for Action—Working with PHP and MySQL 106
Wrapping Things Up and Laying Out the Structure 109
Time for Action—Building the Friendly Application 112
Summary 119
Chapter 4: AJAX Form Validation 121
Implementing AJAX Form Validation 122
Thread-Safe AJAX 125
Time for Action—AJAX Form Validation 126
Summary 144
Chapter 5: AJAX Chat 145
Introducing AJAX Chat 145
Implementing AJAX Chat 147
Time for Action—Ajax Chat 148
Summary 164
ii

Table of Contents
Chapter 6: AJAX Suggest and Autocomplete 165
Introducing AJAX Suggest and Autocomplete 165
Google Suggest 166
Implementing AJAX Suggest and Autocomplete 167
Time for Action—AJAX Suggest and Autocomplete 168
Summary 188
Chapter 7: AJAX Real-Time Charting with SVG 189
Implementing a Real-Time Chart with AJAX and SVG 190
Time for Action—Building the Real-Time SVG Chart 193
Summary 202
Chapter 8: AJAX Grid 203
Implementing the AJAX Grid Using Client-Side XSLT 204
Time for Action—AJAX Grid 205
Summary 221
Chapter 9: AJAX RSS Reader 223
Working with RSS 223
The RSS Document Structure 224
Google Reader 224
Implementing the AJAX RSS Reader 225
Time for Action—Building the RSS Reader Application 226
Summary 236
Chapter 10: AJAX Drag and Drop 237
Using Drag and Drop on the Web 237
Shopping Carts 237
Sortable Lists 238
Building the AJAX Drag-and-Drop Sortable List Application 238
Time for Action—Task Management Application with AJAX 241
Summary 253
Appendix A: Preparing Your Working Environment 255
Preparing Your Windows Playground 256
Installing Apache 256
Installing MySQL 258
Installing PHP 259
iii

Table of Contents
Preparing Your *nix Playground 261
Installing Apache 261
Installing MySQL 261
Installing PHP 262
Installing phpMyAdmin 263
Preparing the AJAX Database 264
Index 267
iv

Preface
AJAX is a complex phenomenon that means different things to different people. Computer users
appreciate that their favorite websites are now friendlier and feel more responsive. Web
developers learn new skills that empower them to create sleek web applications with little effort.
Indeed, everything sounds good about AJAX!
At its roots, AJAX is a mix of technologies that lets you get rid of the evil page reload, which
represents the dead time when navigating from one page to another. Eliminating page reloads is
just one step away from enabling more complex features into websites, such as real-time data
validation, drag and drop, and other tasks that weren't traditionally associated with web
applications. Although the AJAX ingredients are mature (the XMLHttpRequest object, which is
the heart of AJAX, was created by Microsoft in 1999), their new role in the new wave of web
trends is very young, and we'll witness a number of changes before these technologies will be
properly used to the best benefit of the end users. At the time of writing this book, the "AJAX"
name is about just one year old.
AJAX isn't, of course, the answer to all the Web's problems, as the current hype around it may
suggest. As with any other technology, AJAX can be overused, or used the wrong way. AJAX
also comes with problems of its own: you need to fight with browser inconsistencies,
AJAX-specific pages don't work on browsers without JavaScript, they can't be easily
bookmarked by users, and search engines don't always know how to parse them. Also, not
everyone likes AJAX. While some are developing enterprise architectures using JavaScript,
others prefer not to use it at all. When the hype is over, most will probably agree that the middle
way is the wisest way to go for most scenarios.
In AJAX and PHP: Building Responsive Web Applications, we took a pragmatic and safe approach
by teaching relevant patterns and best practices that we think any web developer will need sooner
or later. We teach you how to avoid the common pitfalls, how to write efficient AJAX code, and
how to achieve functionality that is easy to integrate into current and future web applications,
without requiring you to rebuild the whole solution around AJAX. You'll be able to use the
knowledge you learn from this book right away, into your PHP web applications.
We hope you'll find this book useful and relevant to your projects. For the latest details and
updates regarding this book, please visit its mini-site at http://ajaxphp.packtpub.com .
The book's mini-site also contains additional free chapters and resources, which we recommend
you check out when you have the time.

Preface
What This Book Covers
Chapter 1: AJAX and the Future of Web Applications is an initial incursion into the world of
AJAX and the vast possibilities it opens up for web developers and companies, to offer a better
experience to their users. In this chapter you'll also build your first AJAX-enabled web page,
which will give you a first look of the component technologies.
Chapter 2: Client-Side Techniques with Smarter JavaScript will guide you through the
technologies you'll use to build AJAX web clients, using JavaScript, the DOM, the XMLHttpRequest
object, and XML. While not being a complete tutorial for these technologies, you'll be put on the
right track for using them together to build a solid foundation for your future applications.
Chapter 3: Server-Side Techniques with PHP and MySQL completes the theoretical foundation by
presenting how to create smart servers to interact with your AJAX client. You'll learn various
techniques for implementing common tasks, including handling basic JavaScript security and
error-handling problems.
Chapter 4: AJAX Form Validation guides you through creating a modern, responsive, and secure
form validation system that implements both real-time AJAX validation and server-side validation
on form submission.
Chapter 5: AJAX Chat presents a simple online chat that works exclusively using AJAX code, without
using Java applets, Flash code, or other specialized libraries as most chat applications do these days.
Chapter 6: AJAX Suggest and Autocomplete builds a Google Suggest-like feature, that helps you
quickly find PHP functions, and forwards you to the official help page for the chosen function.
Chapter 7: AJAX Real-Time Charting with SVG teaches you how to implement a real-time
charting solution with AJAX and SVG. SVG (Scalable Vector Graphi cs) is a text-based graphics
language that can be used to draw shapes and text.
Chapter 8: AJAX Grid teaches you how to build powerful AJAX-enabled data grids. You'll learn
how to parse XML documents using XSLT to generate the output of your grid.
Chapter 9: AJAX RSS Reader uses the SimpleXML PHP library, XML, and XSLT to build a
simple RSS aggregator.
Chapter 10: AJAX Drag and Drop is a demonstration of using the script.aculo.us framework to
build a simple list of elements with drag-and-drop functionality.
Appendix A: Preparing Your Working Environment teaches you how to install and configure the
required software: Apache, PHP, MySQL, phpMyAdmin. The examples in this book assume that
you have set up your environment and sample database as shown here.
At the book's mini-site at http://ajaxphp.packtpub.com , you can find the online demos for
all the book's AJAX case studies.
2

Preface
What You Need for This Book
To go through the examples of this book you need PHP 5, a web server, and a database server. We
have tested the code under several environments, but mostly with the Apache 2 web server, and
MySQL 4.1 and MySQL 5 databases.
You can choose, however, to use another web server, or another database product, in which case the procedures presented in the chapters might not be 100% accurate. It is important to have PHP 5 or newer, because we use some features, such as Object Oriented Programming support, which
aren't available in older versions.
Please read Appendix A for more details about setting up your machine. If your machine already
has the required software, you still need to read the final part of Appendix A, where you are
instructed about creating a database that is used for the examples in this book.
Conventions
In this book, you will find a number of styles of text that distinguish between different kinds of
information. Here are some examples of these styles, and an explanation of their meaning.
There are three styles for code. Code words in text are shown as follows: "We can include other contexts through the use of the
include directive."
A block of code will be set as follows:
// function calls the server using the XMLHttpRequest object
function process()
{
// retrieve the name typed by the user on the form
name = document.getElementById("myName").value;
// execute the quickstart.php page from the server
xmlHttp.open("GET", "quickstart.php?name=" + name, false);
// make synchronous server request
xmlHttp.send(null);
// read the response
handleServerResponse();
}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items will be made bold:
// function calls the server using the XMLHttpRequest object
function process()
{
// retrieve the name typed by the user on the form
name = document.getElementById("myName").value;
// execute the quickstart.php page from the server
xmlHttp.open("GET", "quickstart.php?name=" + name, false);
// make synchronous server request
xmlHttp.send(null);
// read the response
handleServerResponse();
}
3

Preface
Any command-line input and output is written as follows:
./configure --prefix=/usr/local/apache2 --enable-so --enable-ssl --with-
ssl --enable-auth-digest

New terms and important words are introduced in a bold-type font. Words that you see on the
screen, in menus or dialog boxes for example, appear in our text like this: "clicking the Next
button moves you to the next screen".
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Reader Feedback
Feedback from our readers is always welcome. Let us know what you think about this book, what
you liked or may have disliked. Reader feedback is important for us to develop titles that you
really get the most out of.
To send us general feedback, simply drop an email to [email protected], making sure to
mention the book title in the subject of your message.
If there is a book that you need and would like to see us publish, please send us a note in the
form on SUGGEST A TITLE www.packtpub.com or email [email protected].
If there is a topic that you have expertise in and you are interested in either writing or contributing
to a book, see our author guide on www.packtpub.com/authors .
Customer Support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get
the most from your purchase.
Downloading the Example Code for the Book
Visit http://www.packtpub.com/support , and select this book from the list of titles to
download any example code or extra resources for this book. The files available for download will
then be displayed.
The downloadable files contain instructions on how to use them.
4

Preface
Errata
Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If
you find a mistake in one of our books—maybe a mistake in text or code—we would be grateful if
you would report this to us. By doing this you can save other readers from frustration, and help to
improve subsequent versions of this book. If you find any errata, report them by visiting
http://www.packtpub.com/support , selecting your book, clicking on the Submit Errata
link, and entering the details of your errata. Once your errata have been verified, your submission will be accepted and the errata added to the list of existing errata. The existing errata can be
viewed by selecting your title from
http://www.packtpub.com/support .
Questions
You can contact us at [email protected] if you are having a problem with some aspect
of the book, and we will do our best to address it.
5

1
AJAX and the Future of
Web Applications
"Computer, draw a robot!" said my young cousin to the first computer he had ever seen. (Since I
had instructed it not to listen to strangers, the computer wasn't receptive to this command.) If
you're like me, your first thought would be "how silly" or "how funny"—but this is a mistake. Our
educated and modeled brains have learned how to work with computers to a certain degree. People
are being educated to accommodate computers, to compensate for the lack of ability of computers
to understand humans. (On the other hand, humans can't accommodate very well themselves, but
that's another story.)
This little story is relevant to the way people instinctively work with computers. In an ideal world,
that spoken command should have been enough to have the computer please my cousin. The ability of technology to be user-friendly has evolved very much in the past years, but there's still a
long way till we have real intelligent computers. Until then, people need to learn how to work with computers—some to the extent that they end up loving a black screen with a tiny command
prompt on it.
Not incidentally, the computer-working habits of many are driven by software with user interfaces
that allow for intuitive (and enjoyable) human interaction. This probably explains the popularity of
the right mouse button, the wonder of fancy features such as drag and drop, or that simple text box
that searches content all over the Internet for you in just 0.1 seconds (or so it says). The software
industry (or the profitable part of it, anyway) has seen, analyzed, and learned. Now the market is
full of programs with shiny buttons, icons, windows, and wizards, and people are paying a lot of
money for them.
What the software industry has learned is that the equivalent of a powerful engine in a red sports car is usability and accessibility for software. And it's wonderful when what is good from the
business point of view is also good from a human point of view, because the business profits are
more or less proportional to customers' satisfaction.
We plan to be very practical and concise in this book, but before getting back to your favorite
mission (writing code) it's worth taking a little step back, just to remember what we are doing and
why we are doing it. We love technology to the sound made by each key stroke, so it's very easy
to forget that the very reason technology exists is to serve people and make their lives at home
more entertaining, and at work more efficient.

AJAX and the Future of Web Applications
8
Understanding the way people's brains work would be the key to building the ultimate software
applications. While we're far from that point, what we do understand is that end users need
intuitive user interfaces; they don't really care what operating system they're running as long as the
functionality they get is what they expect. This is a very important detail to keep in mind, as many
programmers tend to think and speak in technical terms even when working with end users
(although in a typical development team the programmer doesn't interact directly with the end
user). If you disagree, try to remember how many times you've said the word database when
talking to a non-technical person.
By observing people's needs and habits while working with computer systems, the term software
usability was born—referring to the art of meeting users' interface expectations, understanding
the nature of their work, and building software applications accordingly.
Historically, usability techniques were applied mainly to desktop applications, simply because
the required tools weren't available for web applications. However, as the Internet gets more
mature, the technologies it enables are increasingly potent.
Modern Internet technologies not only enable you to build a better online presence, but also allow
building better intranet/dedicated applications. Having friendly websites is crucial for online
business, because the Internet never sleeps, and customers frequently migrate to the next "big
thing" that looks better or feels to move faster. At the same time, being able to build friendly web
interfaces gives alternative options for intranet software solutions, which were previously built
mainly as desktop applications.
Building user-friendly software has always been easier with desktop applications than with web
applications, simply because the Web was designed as a means for delivering text and images, and
not complex functionality. This problem has gotten significantly more painful in the last few
years, when more and more software services and functionality are delivered via the Web.
Consequently, many technologies have been developed (and are still being developed) to add flashy
lights, accessibility, and power to web applications. Notable examples include Java applets and
Macromedia Flash, which require the users to install separate libraries into their web browsers.
Delivering Functionality via the Web
Web applications are applications whose functionality is processed on a web server, and is
delivered to the end users over a network such as the Internet or an intranet. The end users use a
thin client (web browser) to run web applications, which knows how to display and execute the
data received from the server. In contrast, desktop applications are based on a thick client (also
called a rich client or a fat client), which does most of the processing.
Web applications evolve dreaming that one day they'll look and behave like their mature (and
powerful) relatives, the desktop applications. The behavior of any computer software that interacts
with humans is now even more important than it used to be, because nowadays the computer user
base varies much more than in the past, when the users were technically sound as well. Now you
need to display good looking reports to Cindy, the sales department manager, and you need to
provide easy-to-use data entry forms to Dave, the sales person.

Chapter 1
Because end-user satisfaction is all that matters, the software application you build must be
satisfactory to all the users that interact with it. As far as web applications are concerned, their
evolution-to-maturity process will be complete when the application's interface and behavior will
not reveal whether the functionality is delivered by the local desktop or comes through fiber or air.
Delivering usable interfaces via the Web used to be problematic simply because features that
people use with their desktop application, such as drag and drop, and performing multiple tasks on
the same window at the same time, were not possible.
Another problem with building web applications is standardization. Today, everything
web-accessible must be verified with at least two or three browsers to ensure that all your visitors
will get the full benefit of your site.
Advantages of Web Applications
Yes, there are lots of headaches when trying to deliver functionality via the Web. But why bother
trying to do that in the first place, instead of building plain desktop applications? Well, even with
the current problems that web applications have with being user-friendly, they have acquired extraordinary popularity because they offer a number of major technological advantages over
desktop applications.
• Web applications are easy and inexpensive to deliver. With web applications, a
company can reduce the costs of the IT department that is in charge of installing the
software on the users' machines. With web applications, all that users need is a
computer with a working web browser and an Internet or intranet connection.
• Web applications are easy and inexpensive to upgrade. Maintenance costs for
software have always been significant. Because upgrading an existing piece of
software is similar to installing a new one, the web applications' advantages
mentioned above apply here as well. As soon as the application on the server
machine is upgraded, everyone gets the new version.
• Web applications have flexible requirements for the end users. Just have your
web application installed on a server—any modern operating system will do—and
you'll be able to use it over the Internet/Intranet on any Mac, Windows, or Linux
machine and so on. If the application is properly built, it will run equally well on any
modern web browser, such as Internet Explorer, Mozilla Firefox, Opera, or Safari.
• Web applications make it easier to have a central data store . When you have
several locations that need access to the same data, having all that data stored in one
place is much easier than having separate databases in each location. This way you
avoid potential data synchronization operations and lower security risks.
In this book we'll further investigate how to use modern web technologies to build better web
applications, to make the most out of the possibilities offered by the Web. But before getting into
the details, let's take a short history lesson.
9

AJAX and the Future of Web Applications
10
Building Websites Since 1990
Although the history of the Internet is a bit longer, 1991 is the year when HyperText Transfer
Protocol (HTTP), which is still used to transfer data over the Internet, was invented. In its first
few initial versions, it didn't do much more than opening and closing connections. The later
versions of HTTP (version 1.0 appeared in 1996 and version 1.1 in 1999) became the protocol that
now we all know and use.
HTTP and HTML
HTTP is supported by all web browsers, and it does very well the job it was conceived for—
retrieving simple web content. Whenever you request a web page using your favorite web
browser, the HTTP protocol is assumed. So, for example, when you type www.mozilla.org in the
location bar of Firefox, it will assume by default that you meant http://www.mozilla.org.
The standard document type of the Internet is HyperText Markup Language (HTML), and it is
built of markup that web browsers understand, parse, and display. HTML is a language that
describes documents' formatting and content, which is basically composed of static text and
images. HTML wasn't designed for building complex web applications with interactive content or
user-friendly interfaces. When you need to get to another HTML page via HTTP, you need to
initiate a full page reload, and the HTML page you requested must exist at the mentioned location,
as a static document, prior to the request. It's obvious that these restrictions don't really encourage
building anything interesting.
Nevertheless, HTTP and HTML are still a very successful pair that both web servers and web
clients (browsers) understand. They are the foundation of the Internet as we know it today. Figure 1.1 shows a simple transaction when a user requests a web page from the Internet using the HTTP protocol:

Figure 1.1: A Simple HTTP Request

Chapter 1

Three points for you to keep in mind:
1. HTTP transactions always happen between a web client (the software making the
request, such as a web browser) and a web server (the software responding to the
request, such as Apache or IIS). From now on in this book, when saying 'client' we
refer to the web client, and when saying 'server' we refer to the web server.
2. The user is the person using the client.
3. Even if HTTP (and its secure version, HTTPS) is arguably the most important
protocol used on the Internet, it is not the only one. Various kinds of web servers use
different protocols to accomplish various tasks, usually unrelated to simple web
browsing. The protocol we'll use most frequently in this book is HTTP, and when we
say 'web request' we'll assume a request using HTTP protocol, unless other protocol
will be mentioned explicitly.
Sure thing, the HTTP-HTML combination is very limited in what it can do—it only enables users
to retrieve static content (HTML pages) from the Internet. To complement the lack of features,
several technologies have been developed.
While all web requests we'll talk about from now on still use the HTTP protocol for transferring
the data, the data itself can be built dynamically on the web server (say, using information from a database), and this data can contain more than plain HTML allowing the client to perform some
functionality rather than simply display static pages.
The technologies that enable the Web to act smarter are grouped in the following two main categories:
• Client-side technologies enable the web client to do more interesting things than
displaying static documents. Usually these technologies are extensions of HTML,
and don't replace it entirely.
• Server-side technologies are those that enable the server to store logic to build web
pages on the fly.
PHP and Other Server-Side Technologies
Server-side web technologies enable the web server to do much more than simply returning the
requested HTML files, such as performing complex calculations, doing object-oriented
programming, working with databases, and much more.
Just imagine how much data processing Amazon must do to calculate personalized product
recommendations for each visitor, or Google when it searches its enormous database to serve your
request. Yes, server-side processing is the engine that caused the web revolution, and the reason
for which Internet is so useful nowadays.
11

AJAX and the Future of Web Applications
12
The important thing to remember is that no matter what happens on the server side, the response
received by the client must be a language that the client understands (obviously)—such as HTML,
which has many limits, as mentioned earlier.
PHP is one of the technologies used to implement server-side logic. Chapter 3 will serve an
introduction to PHP, and we'll use PHP in this book when building the AJAX case studies. It's
good to know, though, that PHP has many competitors, such as ASP.NET (Active Server Pages,
the web development technology from Microsoft), Java Server Pages (JSP), Perl, ColdFusion,
Ruby on Rails, and others. Each of these has its own way of allowing programmers to build
server-side functionality.
PHP is not only a server-side technology but a scripting language as well, which programmers can use to create PHP scripts. Figure 1.2 shows a request for a PHP page called
index.php.This time,
instead of sending back the contents of index.php, the server executes index.php and sends back
the results. These results must be in HTML, or in other language that the client understands.

Figure 1.2: Client Requests a PHP Page
On the server side you'll usually need a database server as well to manage your data. In the case
studies of this book we'll work with MySQL, but the concepts are the same as any other server.
You'll learn the basics of working with databases and PHP in Chapter 3.
However, even with PHP that can build custom-made database-driven responses, the browser still
displays a static, boring, and not very smart web document.
The need for smarter and more powerful functionality on the web client generated a separated set
of technologies, called client-side technologies. Today's browsers know how to parse more than
simple HTML. Let's see how.
JavaScript and Other Client-Side Technologies
The various client-side technologies differ in many ways, starting with the way they get loaded
and executed by the web client. JavaScript is a scripting language, whose code is written in plain
text and can be embedded into HTML pages to empower them. When a client requests an HTML
page, that HTML page can contain JavaScript. JavaScript is supported by all modern web
browsers without requiring users to install new components on the system.
JavaScript is a language in its own right (theoretically it isn't tied to web development), it's
supported by most web clients under any platform, and it has some object-oriented capabilities.
JavaScript is not a compiled language so it's not suited for intensive calculations or writing device
drivers and it must arrive in one piece at the client browser to be interpreted so it is not secure
either, but it does a good job when used in web pages.

Chapter 1
With JavaScript, developers could finally build web pages with snow falling over them, with
client-side form validation so that the user won't cause a whole page reload (incidentally losing all
typed data) if he or she forgot to supply all the details (such as password, or credit card number),
or if the email address had an incorrect format. However, despite its potential, JavaScript was
never used consistently to make the web experience truly user friendly, similar to that of users of
desktop applications.
Other popular technologies to perform functionality at the client side are Java applets and
Macromedia Flash. Java applets are written in the popular and powerful Java language, and are
executed through a Java Virtual Machine that needs to be installed separately on the system.
Java applets are certainly the way to go for more complex projects, but they have lost the
popularity they once had over web applications because they consume many system resources.
Sometimes they even need long startup times, and are generally too heavy and powerful for the small requirements of simple web applications.
Macromedia Flash has very powerful tools for creating animations and graphical effects, and it's
the de-facto standard for delivering such kind of programs via the Web. Flash also requires the
client to install a browser plug-in. Flash-based technologies become increasingly powerful, and
new ones keep appearing.
Combining HTML with a server-side technology and a client-side technology, one can end up
building very powerful web solutions.
What's Been Missing?
So there are options, why would anyone want anything new? What's missing?
As pointed out in the beginning of the chapter, technology exists to serve existing market needs. And part of the market wants to deliver more powerful functionality to web clients without using
Flash, Java applets, or other technologies that are considered either too flashy or heavy-weight for
certain purposes. For these scenarios, developers have usually created websites and web
applications using HTML, JavaScript, and PHP (or another server-side technology). The typical
request with this scenario is shown in Figure 1.3, which shows an HTTP request, the response
made up of HTML and JavaScript built programmatically with PHP.

Figure 1.3: HTTP, HTML, PHP, and JavaScript in Action
13

AJAX and the Future of Web Applications
14
The hidden problem with this scenario is that each time the client needs new data from the server,
a new HTTP request must be made to reload the page, freezing the user's activity. The page
reload is the new evil in the present day scenario, and AJAX comes in to our rescue.
Understanding AJAX
AJAX is an acronym for Asynchronous JavaScript and XML. If you think it doesn't say much, we
agree. Simply put, AJAX can be read "empowered JavaScript", because it essentially offers a technique
for client-side JavaScript to make background server calls and retrieve additional data as needed,
updating certain portions of the page without causing full page reloads. Figure 1.4 offers a visual
representation of what happens when a typical AJAX-enabled web page is requested by a visitor:

Figure 1.4: A Typical AJAX Call
When put in perspective, AJAX is about reaching a better balance between client functionality and
server functionality when executing the action requested by the user. Up until now, client-side
functionality and server-side functionality were regarded as separate bits of functionality that work
one at a time to respond to user's actions. AJAX comes with the solution to balance the load
between the client and the server by allowing them to communicate in the background while the
user is working on the page.
To explain with a simple example, consider web forms where the user is asked to write some data
(such as name, email address, password, credit card, etc) that has to be validated before reaching
the business tier of your application. Without AJAX, there were two form validation techniques.
The first was to let the user type all the required data, let him or her submit the page, and perform
the validation on the server. In this scenario the user experiences a dead time while waiting for the
new page to load. The alternative was to do this verification at the client, but this wasn't always
possible (or feasible) because it implied loading too much data on the client (just think if you
needed to validate that the entered city and the entered country match).
In the AJAX-enabled scenario, the web application can validate the entered data by making server
calls in the background, while the user keeps typing. For example, after the user selects a country,
the web browser calls the server to load on the fly the list of cities for that country, without

Chapter 1
interrupting the user from his or her current activity. You'll find an example of AJAX form
validation in Chapter 4.
The examples where AJAX can make a difference are endless. To get a better feeling and
understanding of what AJAX can do for you, have a look at these live and popular examples:
• Google Suggest helps you with your Google searches. The functionality is pretty
spectacular; check it out at http://www.google.com/webhp?complete=1 . Similar
functionality is offered by Yahoo! Instant Search, accessible at
http://instant.search.yahoo.com/ . (You'll learn how to build similar
functionality in Chapter 6.)
• GMail (http://www.gmail.com). GMail is very popular by now and doesn't need
any introduction. Other web-based email services such as Yahoo! Mail and Hotmail
have followed the trend and offer AJAX-based functionality.
• Google Maps (http://maps.google.com), Yahoo Maps (http://maps.yahoo.com),
and Windows Live Local (http://local.live.com).
• Other services, such as http://www.writely.com and http://www.basecamphq.com.
You'll see even more examples over the course of this book.
Just as with any other technology, AJAX can be overused, or used the wrong way. Just
having AJAX on your website doesn't guarantee your website will be better. It depends
on you to make good use of the technology.
So AJAX is about creating more versatile and interactive web applications by enabling web pages
to make asynchronous calls to the server transparently while the user is working. AJAX is a tool
that web developers can use to create smarter web applications that behave better than traditional
web applications when interacting with humans.
The technologies AJAX is made of are already implemented in all modern web browsers, such as
Mozilla Firefox, Internet Explorer, or Opera, so the client doesn't need to install any extra modules
to run an AJAX website. AJAX is made of the following:
• JavaScript is the essential ingredient of AJAX, allowing you to build the client-side
functionality. In your JavaScript functions you'll make heavy use of the Document
Object Model (DOM) to manipulate parts of the HTML page.
• The XMLHttpRequest object enables JavaScript to access the server
asynchronously, so that the user can continue working, while functionality is
performed in the background. Accessing the server simply means making a simple
HTTP request for a file or script located on the server. HTTP requests are easy to
make and don't cause any firewall-related problems.
• A server-side technology is required to handle the requests that come from the
JavaScript client. In this book we'll use PHP to perform the server-side part of the job.
15

AJAX and the Future of Web Applications
For the client-server communication the parts need a way to pass data and understand that data.
Passing the data is the simple part. The client script accessing the server (using the
XMLHttpRequest object) can send name-value pairs using GET or POST. It's very simple to read
these values with any server script.
The server script simply sends back the response via HTTP, but unlike a usual website, the response
will be in a format that can be simply parsed by the JavaScript code on the client. The suggested
format is XML, which has the advantage of being widely supported, and there are many libraries that
make it easy to manipulate XML documents. But you can choose another format if you want (you
can even send plain text), a popular alternative to XML being JavaScript Object Notation (JSON).
This book assumes you already know the taste of the AJAX ingredients, except maybe the
XMLHttpRequest object, which is less popular. However, to make sure we're all on the same page,
we'll have a look together at how these pieces work, and how they work together, in Chapter 2 and
Chapter 3. Until then, for the remainder of this chapter we'll focus on the big picture, and we will
also write an AJAX program for the joy of the most impatient readers.
None of the AJAX components is new, or revolutionary (or at least evolutionary) as the
current buzz around AJAX might suggest: all the components of AJAX have existed
since sometime in 1998. The name AJAX was born in 2005, in Jesse James Garret's
article at http://www.adaptivepath.com/publications/essays/archives/
000385.php, and gained much popularity when used by Google in many of its applications.
What's new with AJAX is that for the first time there is enough energy in the market to
encourage standardization and focus these energies on a clear direction of evolution. As a
consequence, many AJAX libraries are being developed, and many AJAX-enabled
websites have appeared. Microsoft through its Atlas project is pushing AJAX
development as well.
AJAX brings you the following potential benefits when building a new web application:
• It makes it possible to create better and more responsive websites and web applications.
• Because of its popularity, it encourages the development of patterns that help
developers avoid reinventing the wheel when performing common tasks.
• It makes use of existing technologies.
• It makes use of existing developer skills.
• Features of AJAX integrate perfectly with existing functionality provided by web
browsers (say, re-dimensioning the page, page navigation, etc).
Common scenarios where AJAX can be successfully used are:
• Enabling immediate server-side form validation, very useful in circumstances when
it's unfeasible to transfer to the client all the data required to do the validation when
the page initially loads. Chapter 4 contains a form validation case study.
16

Chapter 1
• Creating simple online chat solutions that don't require external libraries such as the
Java Runtime Machine or Flash. You'll build such a program in Chapter 5.
• Building Google Suggest-like functionality, like an example you'll build in Chapter 6.
• More effectively using the power of other existing technologies. In Chapter 7,
you'll implement a real-time charting solution using Scalable Vector Graphics
(SVG), and in Chapter 10, you'll use an external AJAX library to create a simple
drag-and-drop list.
• Coding responsive data grids that update the server-side database on the fly. You'll
create such an application in Chapter 8.
• Building applications that need real-time updates from various external sources. In Chapter 9, you'll create a simple
RSS aggregator.
Potential problems with AJAX are:
• Because the page address doesn't change while working, you can't easily bookmark
AJAX-enabled pages. In the case of AJAX applications, bookmarking has different
meanings depending on your specific application, usually meaning that you need to
save state somehow (think about how this happens with desktop applications—
there's no bookmarking there).
• Search engines may not be able to index all portions of your AJAX application site.
• The Back button in browsers, doesn't produce the same result as with classic web
applications, because all actions happen inside the same page.
• JavaScript can be disabled at the client side, which makes the AJAX application non-
functional, so it's good to have another plan in your site, whenever possible, to avoid
losing visitors.
Finally, before moving on to write your first AJAX program, here are a number of links that may
help you in your journey into the exciting world of AJAX:
• http://ajaxblog.com is an AJAX dedicated blog.
• http://www.fiftyfoureleven.com/resources/programming/xmlhttprequest is a
comprehensive article collection about AJAX.
• http://www.ajaxian.com is the AJAX website of Ben Galbraith and Dion Almaer,
the authors of Pragmatic AJAX.
• http://www.ajaxmatters.com is an informational site about AJAX, containing
loads of very useful links.
• http://ajaxpatterns.org is about reusable AJAX design patterns.
• http://www.ajaxinfo.com is a resource of AJAX articles and links.
• http://dev.fiaminga.com contains many links to various AJAX resources
and tutorials.
17

AJAX and the Future of Web Applications
18
• http://ajaxguru.blogspot.com is a popular AJAX-related web blog.
• http://www.sitepoint.com/article/remote-scripting-ajax is Cameron Adams'
excellent article AJAX: Usable Interactivity with Remote Scripting.
• http://developer.mozilla.org/en/docs/AJAX is Mozilla's page on AJAX.
• http://en.wikipedia.org/wiki/AJAX is the Wikipedia page on AJAX.
The list is by no means complete. If you need more online resources, Google will surely be
available to help. In the following chapters, you'll be presented with even more links, but
more specific to the particular technologies you'll be learning about.
Building a Simple Application with AJAX and PHP
Let's write some code then! In the following pages you'll build a simple AJAX application.
This exercise is for the most impatient readers willing to start coding ASAP, but it
assumes you're already familiar with JavaScript, PHP, and XML. If this is not the case, or
if at any time you feel this exercise is too challenging, feel free to skip to Chapter 2. In
Chapter 2 and Chapter 3 we'll have a much closer look at the AJAX technologies and
techniques and everything will become clear.
You'll create here a simple AJAX web application called quickstart where the user is requested to
write his or her name, and the server keeps sending back responses while the user is writing.
Figure 1.5 shows the initial page, index.html, loaded by the user. (Note that index.html gets
loaded by default when requesting the quickstart web folder, even if the file name is not
explicitly mentioned.)

Figure 1.5: The Front Page of Your Quickstart Application
While the user is typing, the server is being called asynchronously, at regular intervals, to see if it
recognizes the current name. The server is called automatically, approximately one time per second, which explains why we don't need a button (such as a '
Send' button) to notify when we're

Chapter 1
done typing. (This method may not be appropriate for real log-in mechanisms but it's very good to
demonstrate some AJAX functionality.)
Depending on the entered name, the message from the server may differ; see an example in
Figure 1.6.

Figure 1.6: User Receives a Prompt Reply From the Web Application
Check out this example online at http://ajaxphp.packtpub.com/ajax/quickstart
Maybe at first sight there's nothing extraordinary going on there. We've kept this first example
simple on purpose, to make things easier to understand. What's special about this application is
that the displayed message comes automatically from the server, without interrupting the user's
actions. (The messages are displayed as the user types a name). The page doesn't get reloaded to
display the new data, even though a server call needs to be made to get that data. This wasn't
a simple task to accomplish using non-AJAX web development techniques.
The application consists of the following three files:
1. index.html is the initial HTML file the user requests.
2. quickstart.js is a file containing JavaScript code that is loaded on the client along
with index.html. This file will handle making the asynchronous requests to the
server, when server-side functionality is needed.
3. quickstart.php is a PHP script residing on the server that gets called by the
JavaScript code in quickstart.js file from the client.
19

AJAX and the Future of Web Applications
Figure 1.7 shows the actions that happen when running this application:

Figure 1.7: The Diagram Explaining the Inner Works of Your Quickstart Application
Steps 1 through 5 are a typical HTTP request. After making the request, the user needs to wait
until the page gets loaded. With typical (non-AJAX) web applications, such a page reload happens
every time the client needs to get new data from the server.
Steps 5 through 9 demonstrate an AJAX-type call—more specifically, a sequence of asynchronous
HTTP requests. The server is accessed in the background using the XMLHttpRequest object.
During this period the user can continue to use the page normally, as if it was a normal desktop
application. No page refresh or reload is experienced in order to retrieve data from the server and
update the web page with that data.
Now it's about time to implement this code on your machine. Before moving on, ensure you've prepared your working environment as shown in Appendix A, where you're guided through how to
install and set up PHP and Apache, and set up the database used for the examples in this book.
(You won't need a database for this quickstart example.)
20

Chapter 1
All exercises from this book assume that you've installed your machine as shown in
Appendix A. If you set up your environment differently you may need to implement
various changes, such as using different folder names, and so on.
Time for Action—Quickstart AJAX
1. In Appendix A, you're instructed to set up a web server, and create a web-accessible
folder called ajax to host all your code for this book. Under the ajax folder, create a
new folder called quickstart.
2. In the quickstart folder, create a file called index.html, and add the following
code to it:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>AJAX with PHP: Quickstart</title>
<script type="text/javascript" src="quickstart.js"></script>
</head>
<body onload='process()'>
Server wants to know your name:
<input type="text" id="myName" />
<div id="divMessage" />
</body>
</html>
3. Create a new file called quickstart.js, and add the following code:
// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();

// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject()
{
// will store the reference to the XMLHttpRequest object
var xmlHttp;
// if running Internet Explorer
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
xmlHttp = false;
}
}
// if running Mozilla or other browsers
else
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
xmlHttp = false;
}
}
// return the created object or display an error message
if (!xmlHttp)
21

AJAX and the Future of Web Applications
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}

// make asynchronous HTTP request using the XMLHttpRequest object
function process()
{
// proceed only if the xmlHttp object isn't busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
// retrieve the name typed by the user on the form
name = encodeURIComponent(document.getElementById("myName").value);
// execute the quickstart.php page from the server
xmlHttp.open("GET", "quickstart.php?name=" + name, true);
// define the method to handle server responses
xmlHttp.onreadystatechange = handleServerResponse;
// make the server request
xmlHttp.send(null);
}
else
// if the connection is busy, try again after one second
setTimeout('process()', 1000);
}

// executed automatically when a message is received from the server
function handleServerResponse()
{
// move forward only if the transaction has completed
if (xmlHttp.readyState == 4)
{
// status of 200 indicates the transaction completed successfully
if (xmlHttp.status == 200)
{
// extract the XML retrieved from the server
xmlResponse = xmlHttp.responseXML;
// obtain the document element (the root element) of the XML structure
xmlDocumentElement = xmlResponse.documentElement;
// get the text message, which is in the first child of
// the the document element
helloMessage = xmlDocumentElement.firstChild.data;
// update the client display using the data received from the server
document.getElementById("divMessage").innerHTML =
'<i>' + helloMessage + '</i>';
// restart sequence
setTimeout('process()', 1000);
}
// a HTTP status different than 200 signals an error
else
{
alert("There was a problem accessing the server: " +
xmlHttp.statusText);
}
}
}
4. Create a file called quickstart.php and add the following code to it:
<?php
// we'll generate XML output
header('Content-Type: text/xml');
// generate XML header
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
// create the <response> element
echo '<response>';
22

Chapter 1
// retrieve the user name
$name = $_GET['name'];
// generate output depending on the user name received from client
$userNames = array('CRISTIAN', 'BOGDAN', 'FILIP', 'MIHAI', 'YODA');
if (in_array(strtoupper($name), $userNames))
echo 'Hello, master ' . htmlentities($name) . '!';
else if (trim($name) == '')
echo 'Stranger, please tell me your name!';
else
echo htmlentities($name) . ', I don\'t know you!';
// close the <response> element
echo '</response>';
?>
5. Now you should be able to access your new program by loading http://localhost/
ajax/quickstart using your favorite web browser. Load the page, and you should
get a page like those shown in Figures 1.5 and 1.6.
Should you encounter any problems running the application, check that you correctly
followed the installation and configuration procedures as described in Appendix A. Most
errors happen because of small problems such as typos. In Chapter 2 and Chapter3 you'll
learn how to implement error handling in your JavaScript and PHP code.
What Just Happened?
Here comes the fun part—understanding what happens in that code. (Remember that we'll discuss
much more technical details over the following two chapters.)
Let's start with the file the user first interacts with, index.html. This file references the mysterious
JavaScript file called quickstart.js, and builds a very simple web interface for the client. In the
following code snippet from index.html, notice the elements highlighted in bold:
<body onload='process()'>
Server wants to know your name:
<input type="text" id="myName" />
<div id="divMessage" />
</body>
When the page loads, a function from quickstart.js called process() gets executed. This
somehow causes the <div> element to be populated with a message from the server.
Before seeing what happens inside the process() function, let's see what happens at the server
side. On the web server you have a script called quickstart.php that builds the XML message to
be sent to the client. This XML message consists of a <response> element that packages the
message the server needs to send back to the client:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
... message the server wants to transmit to the client ...
</response>
23

AJAX and the Future of Web Applications
24
If the user name received from the client is empty, the message will be, "Stranger, please tell me your
name!". If the name is Cristian, Bogdan, Filip, Mihai, or Yoda, the server responds with "Hello, master
<user name>!". If the name is anything else, the message will be "<user name>, I don't know you!".
So if Mickey Mouse types his name, the server will send back the following XML structure:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
Mickey Mouse, I don't know you!
</response>
The quickstart.php script starts by generating the XML document header and the opening
<response> element:
<?php
// we'll generate XML output
header('Content-Type: text/xml');
// generate XML header
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
// create the <response> element
echo '<response>';
The highlighted header line marks the output as an XML document, and this is important because
the client expects to receive XML (the API used to parse the XML on the client will throw an
error if the header doesn't set Content-Type to text/xml). After setting the header, the code builds
the XML response by joining strings. The actual text to be returned to the client is encapsulated in
the <response> element, which is the root element, and is generated based on the name received
from the client via a GET parameter:
// retrieve the user name
$name = $_GET['name'];
// generate output depending on the user name received from client
$userNames = array('CRISTIAN', 'BOGDAN', 'FILIP', 'MIHAI', 'YODA');
if (in_array(strtoupper($name), $userNames))
echo 'Hello, master ' . htmlentities($name) . '!';
else if (trim($name) == '')
echo 'Stranger, please tell me your name!';
else
echo htmlentities($name) . ', I don\'t know you!';
// close the <response> element
echo '</response>';
?>
The text entered by the user (which is supposed to be the user's name) is sent by the client to the
server using a GET parameter. When sending this text back to the client, we use the htmlentities
PHP function to replace special characters with their HTML codes (such as &, or >), making sure
the message will be safely displayed in the web browser eliminating potential problems and security risks.
Formatting the text on the server for the client (instead of doing this directly at the client) is
actually a bad practice when writing production code. Ideally, the server's responsibility is
to send data in a generic format, and it is the recipient's responsibility to deal with security
and formatting issues. This makes even more sense if you think that one day you may need
to insert exactly the same text into a database, but the database will need different
formatting sequences (in that case as well, a database handling script would do the
formatting job, and not the server). For the quickstart scenario, formatting the HTML in
PHP allowed us to keep the code shorter and simpler to understand and explain.

Chapter 1
If you're curious to test quickstart.php and see what it generates, load http://localhost/
ajax/quickstart/quickstart.php?name=Yoda in your web browser. The advantage of sending
parameters from the client via GET is that it's very simple to emulate such a request using your web
browser, since GET simply means that you append the parameters as name/value pairs in the URL
query string. You should get something like this:

Figure 1.8: The XML Data Generated by quickstart.php
This XML message is read on the client by the handleServerResponse() function in
quickstart.js. More specifically, the following lines of code extract the "Hello, master
Yoda!" message:
// extract the XML retrieved from the server
xmlResponse = xmlHttp.responseXML;
// obtain the document element (the root element) of the XML structure
xmlDocumentElement = xmlResponse.documentElement;
// get the text message, which is in the first child of
// the document element
helloMessage = xmlDocumentElement.firstChild.data;
Here, xmlHttp is the XMLHttpRequest object used to call the server script quickstart.php from
the client. Its responseXML property extracts the retrieved XML document. XML structures are
hierarchical by nature, and the root element of an XML document is called the document element.
In our case, the document element is the <response> element, which contains a single child,
which is the text message we're interested in. Once the text message is retrieved, it's displayed on
the client's page by using the DOM to access the divMessage element in index.html:
// update the client display using the data received from the server
document.getElementById('divMessage').innerHTML = helloMessage;
document is a default object in JavaScript that allows you to manipulate the elements in the HTML
code of your page.
The rest of the code in quickstart.js deals with making the request to the server to obtain the
XML message. The createXmlHttpRequestObject() function creates and returns an instance of
the XMLHttpRequest object. This function is longer than it could be because we need to make it
25

AJAX and the Future of Web Applications
26
cross-browser compatible—we'll discuss the details in Chapter 2, for now it's important to know
what it does. The XMLHttpRequest instance, called xmlHttp, is used in process() to make the
asynchronous server request:
// make asynchronous HTTP request using the XMLHttpRequest object
function process()
{
// proceed only if the xmlHttp object isn't busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
// retrieve the name typed by the user on the form
name = encodeURIComponent(document.getElementById("myName").value);
// execute the quickstart.php page from the server
xmlHttp.open("GET", "quickstart.php?name=" + name, true);
// define the method to handle server responses
xmlHttp.onreadystatechange = handleServerResponse;
// make the server request
xmlHttp.send(null);
}
else
// if the connection is busy, try again after one second
setTimeout('process()', 1000);
}
What you see here is, actually, the heart of AJAX—the code that makes the asynchronous call to
the server.
Why is it so important to call the server asynchronously? Asynchronous requests, by their nature,
don't freeze processing (and user experience) while the call is made, until the response is received.
Asynchronous processing is implemented by event-driven architectures, a good example being the
way graphical user interface code is built: without events, you'd probably need to check
continuously if the user has clicked a button or resized a window. Using events, the button notifies
the application automatically when it has been clicked, and you can take the necessary actions in
the event handler function. With AJAX, this theory applies when making a server request—you
are automatically notified when the response comes back.
If you're curious to see how the application would work using a synchronous request, you need
to change the third parameter of xmlHttp.open to false, and then call handleServerResponse
manually, as shown below. If you try this, the input box where you're supposed to write your
name will freeze when the server is contacted (in this case the freeze length depends largely on the
connection speed, so it may not be very noticeable if you're running the server on the local machine).
// function calls the server using the XMLHttpRequest object
function process()
{
// retrieve the name typed by the user on the form
name = encodeURIComponent(document.getElementById("myName").value);
// execute the quickstart.php page from the server
xmlHttp.open("GET", "quickstart.php?name=" + name, false);
// make synchronous server request (freezes processing until completed)
xmlHttp.send(null);
// read the response
handleServerResponse();
}
The process() function is supposed to initiate a new server request using the XMLHttpRequest
object. However, this is only possible if the XMLHttpRequest object isn't busy making another

Chapter 1
request. In our case, this can happen if it takes more than one second for the server to reply, which
could happen if the Internet connection is very slow. So, process() starts by verifying that it is
clear to initiate a new request:
// make asynchronous HTTP request using the XMLHttpRequest object
function process()
{
// proceed only if the xmlHttp object isn't busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
So, if the connection is busy, we use setTimeout to retry after one second (the function's second
argument specifies the number of milliseconds to wait before executing the piece of code specified
by the first argument:
// if the connection is busy, try again after one second
setTimeout('process()', 1000);
If the line is clear, you can safely make a new request. The line of code that prepares the server
request but doesn't commit it is:
// execute the quickstart.php page from the server
xmlHttp.open("GET", 'quickstart.php?name=' + name, true);
The first parameter specifies the method used to send the user name to the server, and you can
choose between GET and POST (learn more about them in Chapter 3). The second parameter is the
server page you want to access; when the first parameter is GET, you send the parameters as
name/value pairs in the query string. The third parameter is true if you want the call to be made
asynchronously. When making asynchronous calls, you don't wait for a response. Instead, you
define another function to be called automatically when the state of the request changes:
// define the method to handle server responses
xmlHttp.onreadystatechange = handleServerResponse;
Once you've set this option, you can rest calm—the handleServerResponse function will be
executed by the system when anything happens to your request. After everything is set up, you
initiate the request by calling XMLHttpRequest's send method:
// make the server request
xmlHttp.send(null);
}
Let's now look at the handleServerResponse function:
// executed automatically when a message is received from the server
function handleServerResponse()
{
// move forward only if the transaction has completed
if (xmlHttp.readyState == 4)
{
// status of 200 indicates the transaction completed successfully
if (xmlHttp.status == 200)
{
The handleServerResponse function is called multiple times, whenever the status of the request
changes. Only when xmlHttp.readyState is 4 will the server request be completed so you can
move forward to read the results. You can also check that the HTTP transaction reported a status of 200, signaling that no problems happened during the HTTP request. When these conditions are
met, you're free to read the server response and display the message to the user.
27

AJAX and the Future of Web Applications
28
After the response is received and used, the process is restarted using the setTimeout function,
which will cause the process() function to be executed after one second (note though that it's not
necessary, or even AJAX specific, to have repetitive tasks in your client-side code):
// restart sequence
setTimeout('process()', 1000);
Finally, let's reiterate what happens after the user loads the page (you can refer to Figure 1.7 for a
visual representation):
1. The user loads index.html (this corresponds to steps 1-4 in Figure 1.7).
2. User starts (or continues) typing his or her name (this corresponds to step 5 in Figure 1.7).
3. When the process() method in quickstart.js is executed, it calls a server script
named quickstart.php asynchronously. The text entered by the user is passed on
the call as a query string parameter (it is passed via GET). The handeServerResponse
function is designed to handle request state changes.
4. quickstart.php executes on the server. It composes an XML document that
encapsulates the message the server wants to transmit to the client.
5. The handleServerResponse method on the client is executed multiple times as the
state of the request changes. The last time it's called is when the response has been
successfully received. The XML is read; the message is extracted and displayed on
the page.
6. The user display is updated with the new message from the server, but the user can
continue typing without any interruptions. After a delay of one second, the process is
restarted from step 2.
Summary
This chapter was all about a quick introduction to the world of AJAX. In order to proceed with
learning how to build AJAX applications, it's important to understand why and where they are
useful. As with any other technology, AJAX isn't the answer to all problems, but it offers means to
solve some of them.
AJAX combines client-side and server-side functionality to enhance the user experience of your
site. The XMLHttpRequest object is the key element that enables the client-side JavaScript code to
call a page on the server asynchronously. This chapter was intentionally short and probably has
left you with many questions—that's good! Be prepared for a whole book dedicated to answering
questions and demonstrating lots of interesting functionality!

2
Client-Side Techniques with
Smarter JavaScript
It is said that one picture is worth a thousand words. And so is a well-written piece of code,
we would say. You will get plenty of both, while building the foundations for your future
AJAX-enabled applications, in this chapter and the next.
Hopefully, the first chapter has developed your interest in AJAX well enough that you will endure
a second chapter with lots of theory to be learned. On the other hand, if you found the first
exercise too challenging, be assured that this time we will advance a bit slower. We will learn the
theory in parts by going through many short examples. In this chapter, we will meet client AJAX
technologies, which include:
• JavaScript
• The JavaScript DOM
• Cascading Style Sheets (CSS)
• The XMLHttpRequest object
• Extensible Markup Language (XML)
You will learn how to make these components work together smoothly, and form a strong
foundation for your future AJAX applications. You will see how to implement efficient error
handling techniques, and how to write code efficiently. Chapter 3 will complete the foundations
by presenting the techniques and technologies that you use on the server; in our case, PHP,
MySQL, and others.
To be a good AJAX developer you need to know very well how its ingredients work separately, and then master how to make them work together. In this book, we assume you have some
experience with at least a part of these technologies.
Depending on your experience level, take some time—before, while, or after reading Chapter 2 or
Chapter 3, to have a look at Appendix B on http://ajaxphp.packtpub.com , which shows you a
number of tools that make a programmer's life much easier. Don't skip it, because it's important, as
having the right tools and using them efficiently can make a very big difference.
You can see all the example applications from this book online at http://ajaxphp.packtpub.com/ .

Client-Side Techniques with Smarter JavaScript
30
JavaScript and the Document Object Model
As mentioned in Chapter 1, JavaScript is the heart of AJAX. JavaScript has a similar syntax
to the good old C language. JavaScript is a parsed language (not compiled), and it has some
Object-Oriented Programming (OOP) capabilities. JavaScript wasn't meant for building large
powerful applications, but for writing simple scripts to implement (or complement) a web
application's client-side functionality (however, new trends are tending to transform JavaScript
into an enterprise-class language—it remains to be seen how far this will go).
JavaScript is fully supported by the vast majority of web browsers. Although it is possible to
execute JavaScript scripts by themselves, they are usually loaded on the client browsers together
with HTML code that needs their functionality. The fact that the entire JavaScript code must arrive
unaltered at the client is a strength and weakness at the same time, and you need to consider these
aspects before deciding upon a framework for your web solution. You can find very good
introductions to JavaScript at the following web links:
• http://www.echoecho.com/javascript.htm
• http://www.devlearn.com/javascript/jsvars.html
• http://www.w3schools.com/js/default.asp
Part of JavaScript's power on the client resides in its ability to manipulate the parent HTML
document, and it does that through the DOM interface. The DOM is available with a multitude of
languages and technologies, including JavaScript, Java, PHP, C#, C++, and so on. In this chapter,
you will see how to use the DOM with both JavaScript and PHP. The DOM has the ability to
manipulate (create, modify, parse, search, etc.) XML-like documents, HTML included.
On the client side, you will use the DOM and JavaScript to:
• Manipulate the HTML page while you are working on it
• Read and parse XML documents received from the server
• Create new XML documents
On the server side, you can use the DOM and PHP to:
• Compose XML documents, usually for sending them to the client
• Read XML documents received from various sources
Two good introductions to DOM can be found at http://www.quirksmode.org/dom/intro.html
and http://www.javascriptkit.com/javatutors/dom.shtml . Play a nice DOM game here:
http://www.topxml.com/learning/games/b/default.asp . A comprehensive reference of the
JavaScript DOM can be found at http://krook.org/jsdom/. The Mozilla reference for the JavaScript
DOM is available at http://www.mozilla.org/docs/dom/reference/javascript.html .
In the first example of this chapter, you will use the DOM from JavaScript to manipulate the
HTML document. When adding JavaScript code to an HTML file, one option is to write the
JavaScript code in a <script> element within the <body> element. Take the following HTML file
for example, which executes some simple JavaScript code when loaded. Notice the document
object, which is a default object in JavaScript that interacts with the DOM of the HTML page.
Here we use its write method to add content to the page:

Chapter 2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>AJAX Foundations: JavaScript and DOM</title>
<script type="text/javascript">
// declaring new variables
var date = new Date();
var hour = date.getHours();
// demonstrating the if statement
if (hour >= 22 || hour <= 5)
document.write("You should go to sleep.");
else
document.write("Hello, world!");
</script>
</head>
<body>
</body>
</html>
The document.write commands generate output that is added to the <body> element of the page
when the script executes. The content that you generate becomes part of the HTML code of the
page, so you can add HTML tags in there if you want.
We advise you try to write well-formed and valid HTML code when possible. Writing code
compliant to HTML format maximizes the chances that your pages will work fine with most existing and future web browsers. A useful article about following web standards can be found at
http://www.w3.org/QA/2002/04/Web-Quality . You can find a useful explanation of the DOCTYPE
element at http://www.alistapart.com/stories/doctype/ . The debate on standards seems to
be an endless one, with one group of people being very passionate about strictly following the
standards, while others are just interested in their pages looking good on a certain set of browsers.
The examples in this book contain valid HTML code, with the exception of a few cases where we
broke the rules a little bit in order to make the code easier to understand. A real fact is that very
few online websites follow the standards, for various reasons.
You will usually prefer to write the JavaScript code in a separate .js file that is referenced from
the .html file. This allows you to keep the HTML code clean and have all the JavaScript code
organized in a single place. You can reference a JavaScript file in HTML code by adding a child
element called <script> to the <head> element, like this:
<html>
<head>
<script type="text/javascript" src="file.js"></script>
</head>
</html>
Even if you don't have any code between <script> and </script> tags, don't be
tempted to use the short form <script type="text/javascript" src="file.js" />
This causes problems with Internet Explorer 6, which doesn't load the JavaScript page.
31

Client-Side Techniques with Smarter JavaScript
32
Let's do a short exercise.
Time for Action—Playing with JavaScript and the DOM
1. Create a folder called foundations in your ajax folder. This folder will be used for
all the examples in this chapter and the next chapter.
2. In the foundations folder, create a subfolder called jsdom.
3. In the jsdom folder, add a file called jsdom.html, with the following code in it:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>AJAX Foundations: JavaScript and DOM</title>
<script type="text/javascript" src="jsdom.js"></script>
</head>
<body>
I love you!
</body>
</html>
4. In the same folder create a file called jsdom.js, and write this code in the file:
// declaring new variables
var date = new Date();
var hour = date.getHours();
// demonstrating the if statement
if (hour >= 22 || hour <= 5)
document.write("Goodnight, world!");
else
document.write("Hello, world!");
5. Load http://localhost/ajax/foundations/jsdom/jsdom.html in your
web browser, and assuming it's not late enough, expect to see the message as
shown in Figure 2.1 (if it's past 10 PM, the message would be a bit different, but
equally romantic).

Figure 2.1: The Hello World Example with JavaScript and the DOM
What Just Happened?
The code is very simple indeed and hence it doesn't need too many explanations. Here are the
main ideas you need to understand:

Chapter 2
• Because there is no server-side script involved (such as PHP code), you can load
the file in your web browser directly from the disk, locally, instead of accessing it
through an HTTP web server. If you execute the file directly from disk, a web
browser would likely open it automatically using a local address such as
file:///C:/Apache2/htdocs/ajax/foundations/jsdom/jsdom.html .
• When loading an HTML page with JavaScript code from a local location (file://)
rather than through a web server (http://), Internet Explorer may warn you that
you're about to execute code with high privileges (more on security in Chapter 3).
• JavaScript doesn't require you to declare the variables, so in theory you can avoid the
var keywords. This isn't a recommended practice though.
• The JavaScript script executes automatically when you load the HTML file. You
can, however, group the code in JavaScript functions, which only execute when
called explicitly.
• The JavaScript code is executed before parsing the other HTML code, so its output
is displayed before the HTML output. Notice that "Hello World!"appears before
"I love you!".
One of the problems of the presented code is that you have no control in the JavaScript code over
where the output should be displayed. As it is, the JavaScript output appears first, and the contents
of the <body> element come next. Needless to say, this scenario isn't relevant even to the simplest
of applications.
Except for the most simple of cases, having just JavaScript code that executes unconditionally
when the HTML page loads is not enough. You will usually want to have more control over when
and how portions of JavaScript code execute, and the most typical scenario is when you use
JavaScript functions, and execute these functions when certain events (such as clicking a button)
on the HTML page are triggered.
JavaScript Events and the DOM
In the next exercise, we will create an HTML structure from JavaScript code. When preparing to
build a web page that has dynamically generated parts, you first need to create its template (which
contains the static parts), and use placeholders for the dynamic parts. The placeholders must be
uniquely identifiable HTML elements (elements with the ID attribute set). So far we have used the
<div> element as placeholder, but you will meet more examples over the course of this book.
Take a look at the following HTML document:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>AJAX Foundations: More JavaScript and DOM</title>
</head>
<body>
Hello Dude! Here's a cool list of colors for you:
<br/>
<ul>
<li>Black</li>
33

Client-Side Techniques with Smarter JavaScript
34
<li>Orange</li>
<li>Pink</li>
</ul>
</body>
</html>
Suppose that you want to have everything in the <ul> element generated dynamically. The typical
way to do this in an AJAX application is to place a named, empty <div> element in the place
where you want something to be generated dynamically:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>AJAX Foundations: More JavaScript and DOM</title>
</head>
<body>
Hello Dude! Here's a cool list of colors for you:
<br/>
<div id="myDivElement"/>
</body>
</html>
In this example we will use the <div> element to populate the HTML document from JavaScript
code, but keep in mind that you're free to assign ids to all kinds of HTML elements. When adding
the <ul> element to the <div> element, after the JavaScript code executes, you will end up with
the following HTML structure:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>Colors</title>
</head>
<body>
Hello Dude! Here's a cool list of colors for you:
<br/>
<div id="myDivElement">
<ul>
<li>Black</li>
<li>Orange</li>
<li>Pink</li>
</ul>
</div>
</body>
</html>
Your goals for the next exercise are:
• Access the named <div> element programmatically from the JavaScript function.
• Having the JavaScript code execute after the HTML template is loaded, so you can
access the <div> element (no HTML elements are accessible from JavaScript code
that executes referenced from the <head> element). You will do that by calling
JavaScript code from the <body> element's onload event.
• Group the JavaScript code in a function for easier code handling.

Chapter 2
Time for Action—Using JavaScript Events and the DOM
1. In the foundations folder that you created in the previous exercise, create a new
folder called morejsdom.
2. In the morejsdom folder, create a file called morejsdom.html, and add the following
code to it:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>AJAX Foundations: More JavaScript and DOM</title>
<script type="text/javascript" src="morejsdom.js"></script>
</head>
<body onload="process()">
Hello Dude! Here's a cool list of colors for you:
<br />
<div id="myDivElement" />
</body>
</html>
3. Add a new file called morejsdom.js, with the following contents:
function process()
{
// Create the HTML code
var string;
string = "<ul>"
+ "<li>Black</li>"
+ "<li>Orange</li>"
+ "<li>Pink</li>"
+ "</ul>";
// obtain a reference to the <div> element on the page
myDiv = document.getElementById("myDivElement");
// add content to the <div> element
myDiv.innerHTML = string;
}
4. Load morejsdom.html in a web browser. You should see a window like the one
in Figure 2.2:

Figure 2.2: Your Little HTML Page in Action
35

Client-Side Techniques with Smarter JavaScript
36
What Just Happened?
The code is pretty simple. In the HTML code, the important details are highlighted in the
following code snippet:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>AJAX Foundations: More JavaScript and DOM</title>
<script type="text/javascript" src="morejsdom.js"></script>
</head>
<body onload="process()">
Hello Dude! Here's a cool list of colors for you:
<br/>
<div id="myDivElement" />
</body>
</html>
Everything starts by referencing the JavaScript source file using the <script> element. The
JavaScript file contains a function called process(), which is used as an event-handler function
for the body's onload event. The onload event fires after the HTML file is fully loaded, so when
the process() function executes, it has access to the whole HTML structure. Your process()
function starts by creating the HTML code you want to add to the div element:
function process()
{
// Create the HTML code
var string;
string = "<ul>"
+ "<li>Black</li>"
+ "<li>Orange</li>"
+ "<li>Pink</li>"
+ "</ul>";
Next, you obtain a reference to myDivElement, using the getElementById function of the
document object. Remember that document is a default object in JavaScript, referencing the body
of your HTML document.
// obtain a reference to the <div> element on the page
myDiv = document.getElementById("myDivElement");
Note that JavaScript allows you to use either single quotes or double quotes for string
variables. The previous line of code can be successfully written like this:
myDiv = document.getElementById('myDivElement');
In the case of JavaScript, both choices are equally good, as long as you are consistent
about using only one of them. If you use both notations in the same script you risk ending
up with parse errors. In this book, we will use double quotes in JavaScript programs.
Finally, you populate myDivElement by adding the HTML code you built in the string variable:
// add content to the <div> element
myDiv.innerHTML = string;
}
In this example, you have used the innerHTML property of the DOM to add the composed HTML
to your document.

Chapter 2
Even More DOM
In the previous exercise, you have created the list of elements by joining strings to compose a
simple HTML structure. The same HTML structure can be built programmatically using the
DOM. In the next exercise, you will generate this content programmatically:
<div id="myDivElement">
Hello Dude! Here's a cool list of colors for you:
<br/>
<ul>
<li>Black</li>
<li>Orange</li>
<li>Pink</li>
</ul>
</div>
A DOM document is a hierarchical structure of elements, where each element can have one or
more attributes. In this HTML fragment, the single element with an attribute is <div>, which has
an attribute called id with the value myDivElement. The root node that you can access through the
document object is <body>. When implementing the above HTML document, you will end up with
a structure such as the one in the figure below:

Figure 2.3: A Hierarchy of HTML Elements
In Figure 2.3, you see an HTML structure formed of <body>, <div>, <br>, <ul>, and <li>
elements, and four text nodes ("Hello…", "Black", "Orange", "Pink"). In the next exercise, you will
create this structure using the DOM functions createElement, createTextNode, and appendChild.
Time for Action—Even More DOM
1. In the foundations folder, create a subfolder called evenmorejsdom.
2. In the evenmorejsdom folder, create a file called evenmorejsdom.html, and add the
following code to it:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>AJAX Foundations: Even More JavaScript and DOM</title>
<script type="text/javascript" src="evenmorejsdom.js"></script>
</head>
37

Client-Side Techniques with Smarter JavaScript
38
<body onload="process()">
<div id="myDivElement" />
</body>
</html>
3. Add a new file called evenmorejsdom.js, with the following contents:
function process()
{
// create the first text node
oHello = document.createTextNode
("Hello Dude! Here's a cool list of colors for you:");

// create the <ul> element
oUl = document.createElement("ul")

// create the first <ui> element and add a text node to it
oLiBlack = document.createElement("li");
oBlack = document.createTextNode("Black");
oLiBlack.appendChild(oBlack);

// create the second <ui> element and add a text node to it
oLiOrange = document.createElement("li");
oOrange = document.createTextNode("Orange");
oLiOrange.appendChild(oOrange);

// create the third <ui> element and add a text node to it
oLiPink = document.createElement("li");
oPink = document.createTextNode("Pink");
oLiPink.appendChild(oPink);

// add the <ui> elements as children to the <ul> element
oUl.appendChild(oLiBlack);
oUl.appendChild(oLiOrange);
oUl.appendChild(oLiPink);

// obtain a reference to the <div> element on the page
myDiv = document.getElementById("myDivElement");

// add content to the <div> element
myDiv.appendChild(oHello);
myDiv.appendChild(oUl);
}
4. Load evenmoredom.html in a web browser. The result should look like Figure 2.4:

Figure 2.4: Even More JavaScript and DOM

Exploring the Variety of Random
Documents with Different Content

the variety of colors suggested a fancy-dress ball. Yet these colors were all
of moderate shades, and Hippolyte Taine himself must have admitted that
very few of them were “loud.” It would not at all surprise me if the world
which has so long laughed at the Englishwoman’s dress should some fine
evening glance into one of these modern interiors and feel as if the ladies
are among the most agreeably dressed of womankind. But I must return
from this digression.
The Misses Garrett appear to have an aim of especial importance in one
particular. They tell me that they have recognized it as a want that a
beautiful decoration should be brought within the reach of the middle-class
families, who are not prepared or disposed to go to the vast expense which
the very wealthy are able and willing to defray, thereby occupying the most
eminent firms. They believe that with care they are able to make beautiful
interiors which shall not be too costly for persons of moderate means. This
can surely be done, but it can only be through a co-operation between the
owners of the house and the decorators which shall make it certain that
there shall be nothing superfluous. If an individual wishes a beautiful home,
especially in dismal London, it is first of all necessary that he or she should
clearly understand what is beautiful, and why it is desired. The decoration
will then, in a sense, be put forth from within, like the foliage of a tree. In
each case the external beauty will respond to an inward want, and be thus
invariably an expression of a high utility. Nowhere more than in the homes
of the great middle classes is there need of beauty. Their besetting fault is a
conventionality which often lapses into vulgarity, and their thoughts (so-
called) are apt to be commonplace. The eye is often starved for the paunch.
The pressure of business sends every man engaged in it home fatigued, and
yet it is only when he enters that home that his real life, his individual and
affectional life, comes into play. On the exchange, in the office or shop, he
has been what commerce and the world determine; he has been but
perfunctory; but now he shuts the door behind him, and his own bit of the
day is reached. What is the real requirement for this person? Does a house
that furnishes him bed and board suffice him? or, which is of greater
importance, does so much alone suffice others who dwell habitually in it?
Here I may mention a work of much importance by J. J. Stevenson, of
the Royal Institute of British Architects, entitled House Architecture. It is in
two volumes—the first devoted to Architecture, the second to House-
planning. The general aim of this work is stated by the author, one of the

ablest and most successful architects in England, in an introductory chapter
from which I quote. “To build a house for one’s self is an excellent
education in architecture. By the time it is finished, and the owner has lived
in it, he feels how much better a house he could build with the experience
he has acquired, if he had to do it over again. While the work is going on
his attention is called to questions he had never thought of before, which are
now of the greatest interest to him. He examines the houses of his friends,
and discovers features in them which he wishes, when too late, he had
introduced in his own plans. The designs are altered and the cost increased.
His taste in architecture and his ideas about planning are changed by his
new experience; the building is too far advanced to adopt the
improvements, and the house which he had hoped would be perfect is a
source of trouble and disappointment. He could build another house to his
mind, but to go through the experience once in a lifetime is enough for most
people. To have, before commencing the building of a new house, the
knowledge which the experience of building gives in some imperfect and
fragmentary way at the end of the process, would save the owner trouble,
expense, and after-regret. To attempt to supply this is the object of this
book.” An admirable book it is! There are a hundred and ninety excellent
wood-cuts in it also. The entire science of lighting, warming, ventilation,
drainage, materials, and construction is here clearly set forth. A man who
has the means to build a house for himself, and who really wishes it to be as
genuinely related to his human self as to the nautilus its shell, should study
carefully this work, unless he can get a better, in which case he will be more
fortunate than I have been.
But Mr. Stevenson’s book does not extend to the decoration of walls
after they are built. The house stands in native worth, but not yet in honor
clad. There ought not to be less reality and utility in the ornamentation of a
house than in its construction. In the ancient Chinese Analects we read that
Kih Tsze-Shing said, “In a superior man it is only the substantial qualities
which are wanted; why should we seek for ornamental accomplishments?”
Tsze-Kung replied, “Ornament is as substance; substance is as ornament:
the hide of a leopard stripped of its hair is like the hide of a dog stripped of
its hair.” It would be difficult to find in literature a finer or more
philosophical statement of the deep basis of Beauty than thus comes to us
from a period of near three thousand years ago, and from a race whose
applications of decorative art to objects of every-day use are models for

Europe. The spots of the leopard are the sum of its history; its hair is the
physiognomy of its passion and power; it bears on its back the tracery of the
leaf and sunshine amid which it hides, and the purpose of the universe hides
with it. Transferred to floor or sofa in a room, the coat of that cat is a bit of
the wild art of nature, full of warm life, purely pictorial; more beautiful than
the skin of our domesticated cats, because these have been adapted to other
purposes, and reduced to an environment of less grandeur. But strip the two
of their hair, and they are only larger and smaller pieces of leather, and the
depilated hide of a dog is the same. All of which confirms Tsze-Kung’s
dictum, that ornament is substance; and it at the same time suggests the
converse truth, that throughout the universe there must be substance to
insure true ornament. When we ascend to the region of finer utilities—
those, namely, which are intellectual, moral, spiritual, social—we discover
that household art is another name for household culture. What germ in the
child’s mind may that picture on the wall be the appointed sunbeam to
quicken? What graceful touch to unfolding character may be added by the
modest tint of a room? Who can say how much falsehood and unreality
have been shed through the life and influence of individuals by tinsel in the
drawing-room and rags up-stairs?
Just now we are the victims of two reactions. Our ancestors made
external beauty everything, and the starved inner life of man rebelled.
Puritanism arose, with grim visage, turning all beautiful things to stone.
From it was bequeathed us a race of artisans who had lost the sense of
beauty. A reaction came, in which the passion for external beauty displayed
itself in an intemperate outbreak of gaudiness and frivolity. We are
sufficiently surrounded by the effects of the reaction, sustained by wealth
without knowledge or taste, to make Charles Eastlake’s description
appropriate to ninety-nine out of every hundred English homes: “This
vitiated taste pervades and infects the judgment by which we are
accustomed to select and approve the objects of every-day life which we
see around us. It crosses our path in the Brussels carpet of our drawing-
rooms; it is about our bed in the shape of gaudy chintz; it compels us to rest
on chairs and to sit at tables which are designed in accordance with the
worst principles of construction, and invested with shapes confessedly
unpicturesque. It sends us metal-work from Birmingham which is as vulgar
in form as it is flimsy in execution. It decorates the finest possible porcelain
with the most objectionable character of ornament. It lines our walls with

silly representations of vegetable life, or with a mass of uninteresting
diaper. It bids us, in short, furnish our houses after the same fashion as we
dress ourselves, and that is with no more sense of real beauty than if art
were a dead letter. It is hardly necessary to say that this is not the opinion of
the general public. In the eyes of materfamilias there is no upholstery which
could possibly surpass that which the most fashionable upholsterer supplies.
She believes in the elegance of window-curtains of which so many dozen
yards were sent to the Duchess of ——, and concludes that the dinner-
service must be perfect which is described as ‘quite a novelty.’” Mr.
Eastlake well says, also: “National art is not a thing which we may enclose
in a gilt frame and hang upon our walls, or which can be locked up in the
cabinet of a virtuoso. To be genuine and permanent, it ought to animate
with the same spirit the blacksmith’s forge and the sculptor’s atelier, the
painter’s studio and the haberdasher’s shop.” Under the influence of such
scornful words as these, persons of taste and culture have risen in reaction
against the reaction, and the result is that there are now in London several
thousands of homes which have filled themselves with those old shreds of
beauty which Puritanism cast to the winds. Most of these are the homes of
artists or virtuosi, and, as they have thus set the fashion, a still larger
number have tried to follow them. A genuinely old thing is competed for
furiously; and as it is apt to go with the longest purse rather than the finest
taste, we find the past as often re-appearing in a domestic curiosity-shop as
in a beautiful interior.
Now, Puritanism in its day was one of the useful things, and if we do not
see the traces of beauty which it has left, the fault is in our own eyes. The
artists know very well that if it had spared the old furniture for the main
uses of our present society, the effect would be as unlovely as if our homes
were all buttressed and turreted in feudal style. Feudalism and Puritanism
have alike left to us just as much of the styles of their ages as we need—
enough to give, as it were, a fair fringe to the appropriate vestment of to-
day. A house made up of antiquarian objects is a show-room, a museum, but
not a home. We have fallen upon an age when cultured people know that
external beauty is but one means to integral beauty, and when the prophets
of that higher end can see that the very flowers of the field are ugly, if they
drink up that which ought to turn to corn and wine. Much is to be said for
the antiquarian taste, if it does not run into an antiquarian passion. It may
safely be admitted that our churches need not be sombre nor our services

gloomy; that a few good pictures would not harm the one, nor more poetry
and music the other; but what is to be said of those who find in albs and
chasubles and incense-burners the regained Paradise of man? Old lamps are
not always better than new.
Much is said from time to time about the ugliness of London street
architecture. I have already quoted the London Times’ sentence about “our
ugly but not altogether uncomfortable old metropolis.” The ugliness is
mentioned at various points of this work. But there are two kinds of it; as
the famous Boston divine said there are two kinds of fools—“the natural
fool, and what the carnal mind, oblivious of its duty, would call a d—fool.”
When Temple Bar was removed from Fleet Street because it was an
impediment, the Corporation of London devoted £10,000 to putting up in
the centre of the street a columnar monstrosity, carved with busts of royal
personages, griffin-crowned. This is the kind of London ugliness which
suggests the definition of the carnal mind. An effort was made in Parliament
to get it removed; but it was too large for Madame Tussaud’s “Chamber of
Horrors;” and perhaps it is as well that it should remain, as the monument
of that vast amount of wealth which is continually embodied in the ugliness
which Puritanism made a passion in the average middle-class Englishman.
But the other kind of London ugliness is represented in the miles on miles
of yellow-gray and sooty, brick houses, each as much like the other as if so
many miles of hollow block were chopped at regular intervals. And yet
there is something so pleasant to think of in these interminable rows of
brick blocks, that they are not altogether unpleasant to the eye. For they are
houses of good size, comfortable houses; and their sameness, only
noticeable through their vast number, means that the average of well-to-do
people in London is also vast. It implies a distribution of wealth, an equality
of conditions, which make the best feature of a solid civilization. There is
much beauty inside these orange-tawny walls. Before any house in that
league of sooty brick you may pause and say with fair security: In that
house are industrious, educated people; there is good music there; and good
English, French, and German literature; pictures of noble men and heroic
events are on the walls; they have made there, within their mass of burnt
clay, a true cosmos, where love and thought dwell with them; and between
all that and a fine outside they have chosen the better part.
But, while not forgetting that the body is more than raiment, we need not
forget that it can never be fairly expressed, in any but a coarse way, save

through the raiment related to it. On this we must insist, that when
individuality has been cultivated there should be an harmonious and organic
relation between the individual and his dwelling-place. In a normal society
each man would be able to build his house around him as he builds his
body, and to take the past, the east, the west, for his materials as much as
brick or stone. “Let us understand,” says the wisest adviser of our time,
“that a house should bear witness in all its economy that human culture is
the end to which it is built and garnished. It stands there under the sun and
moon to ends analogous and not less noble than theirs. It is not for festivity,
it is not for sleep; but the pine and the oak shall gladly descend from the
mountains to uphold the roof of men as faithful and necessary as
themselves, to be the shelter always open to good and true persons—a hall
which shines with sincerity, brows ever tranquil, and a demeanor
impossible to disconcert; whose inmates know what they want; who do not
ask your house how theirs shall be kept.”
One residence particularly has connected itself in the course of my
observations with the high place given, in this extract from Emerson’s
chapter on Domestic Life, to the individuality so essential to a home, and so
difficult to obtain. Those who have found delight—as who has not?—in the
paintings which the American artist, Mr. George S. Boughton, A.R.A., has
given to the world will not be surprised to learn that he has built up around
him a home worthy of his refined taste and his delicate perception of those
laws of beauty which enable it to harmonize with individual feeling without
ever running into eccentricity. Boughton was one of the first to make his
home harmonious with his art, and before he built West House, his present
residence, he made the interior of an ordinary house, Grove Lodge,
Kensington, into a residence as unique as one of those charming pictures of
his which so tenderly invest the human life of to-day with the sentiment and
romance of its own history. Passing once through that hall, touched
everywhere with the toned light of antique beauty, to his studio, the picture
just finished for the Royal Academy appeared as a natural growth out of the
aesthetic atmosphere by which he was surrounded—some girls of
Chaucer’s time beside an old well and a cross, filling the water-bottles of
pilgrims on their way, amid the spring blossoms, to the shrine of St. Thomas
à Becket, “the holy, blissful martyr,” at Canterbury. The embowered English
landscape closed as kindly around the figures and costumes and symbols of
the olden time as they do now about the features of a new age; and no less

harmoniously did the ornaments and decorations of that home surround the
cultured society which the young host and hostess gather to their
assemblies. Although Grove Lodge is no longer the home of the Boughtons,
its decorations were so instructive as well as beautiful, that I insert here an
account of them.
Entering the door, we find ourselves in a square vestibule, separated
from the main hall by rich and heavy curtains of greenish-blue tapestry. The
walls are here, for a distance of one-third of their height from the floor,
covered with a panelled wainscot, colored in harmony with the hangings.
For the rest, the walls are covered with a stamped leather papering of large
antique scrolls, outlined in gold. A rich light fills this little apartment by
reason of the quaint and deep-hued glass of the door and side-window. In
these both roundels and quarries are used. In the door there are roundels
above and quarries beneath, furnishing a neat border to larger stainings,
representing marguerites and clover-blossoms on a blue ground. Above the
door is a curious horizontal glass mosaic, set in lead, as indeed are all the
squares and circlets of both window and door, with bees and butterflies at
the angles of the irregular lines. The zigzag flight of the little winged
symbols of industry and pleasure required that the pieces of glass should be
irregular, and this result was secured by an odd device. The decorator
having come with his oblong pane of precious glass, asked how he should
cut it up. The artist promptly ordered him to let it fall through some feet on
the door-step, and then gather up the fragments. This was done, and as the
pieces came of the fall so were they put together, with the bees and
butterflies at their angles. The effect of this irregularity is very fine indeed,
as setting off the precision of the patterns in the rest of the door.
Passing through the curtains, we enter a hall running about two-thirds of
the depth of the house to the dining-room. The hall is lined with fine old
engravings and cabinets, with here and there an old round convex mirror.
The general color of the walls of the dining-room is sage-green, thus setting
off finely the beautiful pictures and the many pieces of old china. There are
several cabinets which have been designed by Mr. Boughton himself, and a
buffet somewhat resembling that drawn by Charles Eastlake (Fig. 12, Hints
on Household Taste), but improved, as I think, by being made somewhat
higher, and having a small ornamental balustrade on the top shelf. And I
may here say that Mr. Boughton’s art has enabled him to make his many
beautiful cabinets, the antique ones as well as those designed by himself,

particularly attractive by introducing small paintings on the panels of their
doors or drawers. These figures are generally allegorical and decorative,
and are painted upon golden backgrounds. They are of rich but sober colors,
and usually female figures, with flowing drapery, great care being taken that
their faces shall have dignity and expression. In some cases an old cabinet
has small open spaces here and there which will admit of medallion busts
and heads being painted; and if care be taken that the colors shall not be too
loud, and especially that the designs are not realistic, the beauty and value
of the cabinet are very much enhanced. The buffet to which I have referred
has a curtain over the arch beneath, and such an addition may be also made
to a cabinet which rests upon legs with good effect as well as utility, if care
be taken that the color of the curtain shall not be obtrusive.
This dining-room is lighted by a large window set back in a deep recess,
curtained off from the main room with hangings of red velvet, and
exquisitely environed by original designs. The window is composed of the
richest quarries, holding in their centres each its different decorative flower
or other natural form, and these being collectively the frame of large
medallions of stained glass, representing Van Eyck, Van Orley, and the
burgomaster’s wife, from Van Eyck’s picture in the National Gallery.
It is a notable feature of the ideas of glass decoration, and, indeed, of
paper decoration, in houses where English artists have superintended the
ornamentation, that realism in design is severely avoided. In this respect I
cannot doubt that we are in London far more advanced in taste than those
decorators of Munich, and some other Continental cities, who try to make
the figures, in their glass at least, as commonplacely real as if they were
painting on canvas. Even if the material with which the glass-stainer works
admitted of a successful imitation of natural forms, the result could not be
beautiful. No one desires roses to blossom on his window-panes, nor
butterflies to settle on the glass as if it were a flower. The real purpose of
the glass can never be safely forgotten in its decoration: it is to keep out the
cold while admitting the light; the color is to tone the light, and prevent its
being garish; and if, farther, any form is placed upon the glass, it is merely
to prevent monotony by presenting an agreeable variation from mere color.
But the form must be in mere outline, transparent, else it suggests an
opaque body, which were a denial of the main purpose of the glass, i.e., to
do away with opaqueness. Even when the ornaments on the little panes are

thinnest, they are hardly suited to the English sky, which sends us little
superfluous light.
The drawing-room at Grove Lodge was, and that of West House is,
adorned on the theory that its function is one which requires a degree of
richness bordering on brilliancy, which were out of place in a study, or
studio, or sitting-room. Here are to be happy assemblies of light-hearted
people, in gay dresses, and the room must be in harmony with the purpose
of pleasure which has brought them together; but then the drawing-room
must not obtrude itself—it must not outshine their lustres or pale their
colors; rather it must supply the company with an appropriate framing, and
set them all in the best light. The drawing-room at Grove Lodge seemed to
me a purely artistic creation of a beautiful out of a poorly constructed room.
A paper of heraldic pink roses, very faint, with leaves in mottled gold,
makes a frieze of one width above a wall-paper of sage-gray, which has no
discernible figures at all on it. This sage-gray supplies an excellent
background to the pictures—which are moderate in quantity, charming in
quality—and for the picturesque ladies, who are too often fairly blanched
by the upholsterer’s splendor, as they might be by blue and silver lights in a
theatre. At the cornice is a gold moulding and fretting, making an agreeable
fringe to the canopy (as the star-spotted ceiling may be appropriately
called). The ceiling is not stellated, however, with the regularity of wall-
paper designs, but with stars of various magnitude and interspaces. It must
be, of course, a room in which the deep tones of color preponderate which
could alone make such a ceiling appropriate. In this instance it is rendered
appropriate not only by the character of the hangings of the room, at once
rich and subdued, and by the carpet, which Mr. Boughton had made for the
room, the basis of whose design is the greensward, touched here and there
with spots of red, but also by the fact that it is a double drawing-room,
lighted in the daytime only at the ends, and requiring, therefore, a bright
ceiling. There are two old Japanese cabinets: one is richly chased, but with
nothing in relief except the gold lock-plates, and some twenty-eight hinges
(themselves a decoration); the other is more complex, and has figures in
relief. In addition to these there are two cabinets of unique beauty, designed
by Mr. Boughton—one possessing a bevelled mirror running its whole
width at the top; the other with panels, on which the artist has painted
Spring and Autumn in gold.

In this residence some of the best effects were produced by the
extraordinary lustre of color and quality of surface in the stuffs used for
curtains, furniture-covers, and upholstery. These are such as are not
ordinarily manufactured, and can be procured in London only by searching
for them. Manufacturers in this country, and no doubt in America also, are
in the habit of bleaching their stuffs as white as possible, and the
consequence is they will not take rich and warm dyes. The secret of those
Oriental stuffs upon whose surface, as they appear in our exhibitions,
English manufacturers are so often seen looking with despair, is that they
never bleach to whiteness anything that is to be dyed. If the Eastern dyers
should put their deep colors upon a surface bleached to ghastliness, their
stuffs would be as ghastly as our ordinary goods speedily become. The
Oriental dyer simply leaves the natural color of the wool or cotton creamy
and delicate, and the hues never turn out crude and harsh, as do those of
English stuffs. This bleaching, moreover, takes the life out of a natural
material, and is the reason of the superior durability of colored Oriental
fabrics.
Mr. Boughton has named the grand mansion built for him on Campden
Hill, “West House,” in honor of Benjamin West, the first American artist
who received in England honors similar to those which have been accorded
himself. In this house he has had ample room to develop his ideas of
decoration. It is Grove Lodge, as it were, in full flower. An excellent effect
has been secured by giving to each of three large rooms, opening into each
other through richly-draped door-ways, tints of their own; each is different,
while harmonious with its neighbor. It would require a pamphlet to do
justice to all the decorations of West House, and I must content myself with
having already given an extended analysis of the ideas of ornamentation
which our American Academician has done so much to diffuse. But one
thing I must not omit to mention. In the removal to this house a large and
magnificent old bevelled mirror was cracked irregularly across the entire
surface. The eye of the artist detected in the misfortune an opportunity for a
novel touch of decoration. He painted the blemish into a beauty. A beautiful
vine in leaf and blossom now runs across the mirror, which, I hear, has been
imitated by some who have seen it, in ignorance, perhaps, that the pretty
device was suggested by a flaw. Boughton’s mirror might well have an
inscription beneath it from Shakspeare: “Best men are moulded out of
faults.”

Another American artist adorned his London residence in a way quite
notable. The ancient mansion of the Lindsays (300 years old) on the
northern bank of the Thames, at Chelsea, was divided up into six houses,
and one of these was for some years occupied by Mr. Whistler. This
gentleman’s enthusiasm for Japanese and Chinese art is well known; but
that large number of people who are in the habit of holding up their china
plates at dinner as texts from which to descant on the strange ignorance of
drawing and perspective under which the Chinese and Japanese labor,
would find good reason to check their laughter should they be fortunate
enough to see Mr. Whistler’s rooms. The Chinese and Japanese have known
for a good many centuries certain principles of art which Europeans are
only beginning to recognize; one of these is, that a plate or pot is by no
means the proper place for a realistic picture, but, on the contrary, that the
only use of art on such an object is to give it spots of color. The chief object
is not the picture, but the pot. No people know the laws of perspective
better than the Chinese and the Japanese, or have greater realistic power.
Mr. Whistler dots the walls and even the ceiling of his rooms with the
brilliant Japanese fans which now constitute so large an element in the
decoration of many beautiful rooms; but in his drawing-room there were
fifteen large panels made of Japanese pictures, each about five feet by two.
These pictures represent flowers of every hue, and birds of many varieties
and of the richest plumage. The very lustre of nature is on every petal and
on every feather; the eyes of the birds are as gems that emit light, and their
tortuous necks are painted with a boldness which no European art can rival.
The Japanese, when they aim at nature, have the rare courage to paint
nature as it is; and, as a result, the tortuous necks of their birds tell the story
of their reptilian relationship as clearly as it has been told by Professor
Huxley. There are also in the room an ancient Chinese cabinet with a small
pagoda designed on the top, an old Japanese cabinet of quaint construction,
and several screens from the same region, altogether making one of the
most beautiful rooms imaginable. Mr. Whistler did much to light up and
beautify a somewhat dark staircase in his house by giving the walls a lemon
tint above a dado of gold, on which he has painted butterflies such as adorn
the frames of his pictures, and constitute the signature of his work. I have
become convinced, however, by a visit to the beautiful house which
Chambrey Townshend arranged at Wimbledon, that there can be nothing so
suitable for somewhat dark corridors and staircases as a faint rose tint. In

Mr. Townshend’s house, however cold and cheerless the day may be, there
is always a glow of morning light. This gentleman has shown that a sage-
gray paper with simple small squares (such as Messrs. Marshall & Morris
make) furnishes a good dado to support the light tints upon walls not
papered. Where the walls are papered several gentlemen of taste have
substituted for the usual dado, made of somewhat darker paper, one of
matting. If the matting has a dark red stripe the effect is good, but checker
marks are not pleasant. Mr. Ionides, a Greek gentleman, of London,
arranged a remarkably beautiful hall and stairway in his house at Notting
Hill by using a plain straw-colored matting for the continuous dado, uniting
it by an ebonized chairboarding with a light-colored Morris wall-paper. Of
course tiles are sometimes used to make the dado, but either because of
their common use in hotels and public buildings, or for some other reason,
they appear with increasing rarity in private houses in any other capacity
than that of adorning the fireplace. This remark does not include the use of
tiles as plaques, to be hung as works of fine art—a use of them which is
now frequent, and is the means of producing a great deal of beautiful work.
WILLIAM MORRIS.
It is easy to understand that the house in which one resides must have a
large share in determining the decorations which shall be placed in or upon

MOULDING OVER DADO.
it. An historic or semi-palatial mansion of the olden time will require to
have its great halls and stairways and deep rooms illuminated with colors,
and its large spaces intersected with pictorial screens. Mr. William B. Scott,
of whose mural paintings I have already spoken, and whose occupation it is
to study effects of ornamentation, has a happy field for his taste and task in
his residence, Bellevue House, at Chelsea. This mansion merits particular
attention, both on its own account architecturally, and for its decorations,
added recently. These have been chiefly devised by the artist himself in
carrying out the original plan, and add a suggestive and, properly speaking,
imaginative character to the interiors. The house was built, it is said, by the
Adamses, the architects of the Adelphi, in the Strand, where the Society of
Arts holds its meetings (the approach to which is still called Adams Street).
At that time, about a century ago, decorations in the way of carved
mouldings running around door-ways, and passing all round the rooms on
the surbase and dado, were in use. Previously to that time the entire walls
were generally panelled, but then began the system of panelling or boarding
flatly to the height of three feet only, at which height began the lath-and-
plaster wall. Along the top edge of this dado—which, being just over the
height of a chair or table, gives a very well-furnished and comfortable air to
a room, and ought on that account to be again adopted—ran a more or less
ornamental moulding. That mostly used in Bellevue House is carved in
wood, and very good, closely resembling, indeed, those on the best
specimens of Chippendale furniture, which belongs to the same date—
about 1770. I may add here that the demand among artistic designers for a
recurrence to the dado is shown by the increasing frequency with which a
darker paper than that above, with paper cornice, is made to do duty for it.
A hundred years ago the hall of a mansion was a
more important part of the plan, and more
decoratively treated, than now. The entrance is here
divided by folding-doors from the hall proper, which
is ample enough in area to place the stair a good way
back, and to give a correspondingly wide space
above, on the drawing-room landing, filled in the
olden time by a table, cabinet, eight-day standing
clock, and other objects. The ends of the steps were carved, sometimes very
elegantly. But the most ornamental feature then in use was the moulded
ceiling, which was planned in ovals and spandrels, according to the shape

CHIPPENDALE MAHOGANY
MOULDING, BELMONT
HOUSE.
of the room, sometimes with medallions of Cupids, and occasionally with a
picture, representing an emblematic personage or some such matter, in the
centre. A few of these are still to be seen in London. There is one in Knight-
Rider Street, painted by Cipriani. In Bellevue House the two drawing-
rooms possess very pretty arrangements of fan-shaped ornaments and
delicate foliage. These are now “picked out” in colors—blue and white for
the most part—producing an effect resembling that of Wedgwood ware.
The plan on which the rooms of large London
houses were originally arranged was en suite,
entering one through another, connected by double
doors if the walls were thick enough, so that on
great occasions they could be opened throughout.
On either side of the drawing-rooms at Bellevue
House are smaller rooms connected in this way,
one of which is at present used as a library and
evening sitting-room, and, I must also add, as a room on the walls of which
the ever-bourgeoning studies of the idealist take shape and color. The wood-
work—that is to say, the dado, doors, etc.—is painted Indian red, with black
or light yellow edgings; above this the wall is covered by a green pattern,
but the upper part of this surface is divided by painting into panels two feet
deep by a foot and a half wide, the stile, or division, between being half a
foot. The ceiling is, in the centre, a very faint blue, with a darker blue
meeting the cornice (two feet wide); this darker blue—the blue of the sky—
also fills the painted panels, which thus resemble the openings for
ventilation in some Oriental countries. Across these openings a flight of
vermilion birds—Virginian nightingales, plumed and winged by
imagination, red being evidently chosen for bright effect against the blue—
is represented. The birds reappear above the cornice, and stream in pretty
migration round the ceiling, decreasing in size till they nearly disappear.

DRAWING-ROOM OF BELLEVUE HOUSE.
The chimney-piece of this little room is exquisite, and is much like one
designed by Sir E. Landseer, which I saw among his sketches, except that
the jambs were caryatides. The white marble jambs and architraves in Mr.
Scott’s design are diapered with leaves—laurel and ivy—of Indian red
color, and above the chimney-shelf is a second chimney-piece and shelf,
thus giving double accommodation for objects of ornament or use. The
artist’s collection of old china, majolica, and other objects of similar kind
serves to render his chimney-pieces particularly beautiful. I have not seen a
more attractive work of this kind than the chimney-piece in his principal
drawing-room. The jambs here are panelled, the panels being filled with
mirrors, and divided half-way, two feet nine from the floor, by a shelf large
enough to accommodate a lamp or candle, with a teacup or other object.
The arrangement is admirable both for utility and beauty. A supplementary
chimney-shelf is added here, also, to the marble one; and rising nearly to
the ceiling is a surface of black wood, with brackets, for the exhibition of
some very fine old Hispano-Moresque ware, the golden, metallic lustre of
which is favorably seen against the black. The centre is filled by Mr. Scott’s
own most beautiful picture of Eve, which, with a large screen covered with
classical figures, sheds a glory of color through this unique room, which
has, besides, the good fortune to command from its windows the finest
views of the Thames.

Entirely different from either of these residences is that of Mr. George
W. Smalley, the distinguished correspondent of the New York Tribune, in
Chester Place. Birket Foster, George Boughton, W. B. Scott, and J. McNeil
Whistler have naturally decorated their houses with an eye to picturesque
effect; theirs are the homes of men whose daily life is consecrated to art,
and a use of colors seems appropriate to their environment which might not
so well accord with persons differently occupied. Those who have
experienced some of the wear and tear of this busy London existence can
hardly enter the door of this American gentleman without finding a
sufficient justification for the growing desire of families to surround
themselves with household beauty, against all the charges of the puritanical.
“Thus I tread on the pride of Plato,” said Socrates, as he stepped on the
carpet of his famous friend. “With a pride of thy own,” answered Plato, who
is supposed to have got the better in this little encounter. Nature is not
nowadays in such discredit as formerly for having blended beauties with
utilities, making even her pease and potatoes bear graceful blossoms. And
there would appear to be some reason in the tendency of her yet higher
product, a home, to wear a fitting bloom as the sign of its reality. Such a
suggestion is made by the subdued and delicate tints and tones which here
meet the eye. One may have stepped from other houses of this fashionable
neighborhood to find here a sweet surprise. There is, then, no absolute and
eternal law making it compulsory to select ugly things instead of pretty
things. Tinsel is not intrenched in the decalogue. Here is a hall in which
gray and brown shades prevail in dado and paper, where a soft light
prevails, and the garish light and the noise of the street can hardly be
remembered. One may enter the nursery and find the children at play or
study amid walls that bring no shams around their simplicity, no finery, but
sage-gray and straw-color, setting off well their bright faces and those
panels in the bookcase which tell the story of Cinderella.

LIBRARY IN BELLEVUE HOUSE.
To the suite of drawing-rooms every excellence must be ascribed. They
consist of two large rooms and a large recess, all continuous, whose
decorations adapt them to any domestic or social purpose whatever. It is an
apartment in which the finest company would feel itself in an atmosphere of
refinement and taste, and it is a place to lose one’s self in a good book; it is
a place where the mind can equally well find invitation to society or
solitude. Perhaps it is the rich Persian carpet that gives such grace. It is after
a pattern more than a thousand years old, but which in all that time has
never repeated itself, each carpet coming forth with its own tints and
shades, and in which every color is surrounded by a line which mediates
between it and the next. It is not stretched up to the walls and nailed, as if
its business were to conceal something, or as if it were too flimsy to lie still
except by force of iron: it is as a large rug laid for comfort on the waxed
parquet, which is ready to display more of its own beauty when the proper
season arrives. Beginning with this rich carpet, with its sober tints, the eye
ascends to the dado, to the walls, to frieze, cornice, and ceiling, and finds
variation at every stage, but no break in the harmony of all. The golden tints
in the carpet are more fully represented in the dado, which is of an olive-
golden color, with a small turquoise line on its cornice leading to the main
papering. This paper is of a French tapestry pattern, in which the golden
thread, which is its basis, weaves in colors that are rich but always subdued,

and of every shade. There is no pattern to rivet the eye; it has no certain
relation to the vegetal, or floral, or animal kingdom. This paper rises to a
Moresque frieze of about one foot in depth, which holds hexagonal
medallions containing the ghosts of plants. There is next a cornice of three
mouldings—arabesque, Egyptian, and floral—leading to the ceiling, which
is covered with paper of a rich creamy color, with very light cross-bands
passing between figures in which a fertile fancy may trace the decorative
symbols of earth, air, and water in an orb, a butterfly, and certain waving
lines. It may be remarked here that it is only on a ceiling that any forms,
even in such abstract shapes as these, are admissible. Here they are
noticeable only if one is lying flat on one’s back and gazing upward, in
which case, especially if invalidism be the cause, some outlines of a dreamy
kind are not without their value. Moreover, any designs, when raised to the
ceiling, require to be larger than similar ones on the floor or line of the eye,
in order that they may be at all similar in effect. The plan of covering or
coloring the ceiling has a good foundation in the fact that a mere white wall
overhead conveys the sorry impression that the house is left naked in every
corner and spot not likely to be gazed at. The ceiling in Mr. Smalley’s
drawing-room exemplifies, however, one important fact: although a mere
color placed on a ceiling depresses it, a good pattern has just the contrary
effect. By good pattern I mean one that shows a double ground—the lower
one being open work, through which a farther ground is seen. Mrs. Smalley,
whose taste has been the life of the ornamentation of her house, told me that
when this ceiling was being painted the decorated part appeared to rise
more than a foot higher than the blank part.
The wood used in the drawing-room is ebonized, and of it are several
cabinets—one displaying some fine specimens of china—bracket-shelves,
and two remarkably beautiful chimney-pieces, supporting bevelled mirrors,
framed with shelves which display porcelain and other ornaments. The
recess which has been mentioned is what might be better understood,
perhaps, if described as a bay-window. Its chief object is to hold a large
window, in five contiguous sections, which admit a toned light, and have
each a cluster of sunflowers at the centre. This little room has a broad divan,
covered with stamped green (Utrecht) velvet, running around, and its wall is
decorated with gold-tinted leather, on which are two bright tile ornaments.
The large opening into this recess is adorned by two antique bronze reliefs
of great beauty, and the whole is related to the drawing-rooms by an open

drapery of greenish-golden curtains—a velvet of changeable lustre—
uniform with the other hangings of these beautiful rooms.
It is remarkable, indeed, how much may be accomplished with rooms
inferior in size to those we have been visiting by the skilful use of curtains.
If a gentleman in London enters a house with the intention of decorating it
in accordance with principles of art, his first work, probably, will be either
to tear away doors that divide the drawing-room, and substitute a draping,
or else frame it round with looped and corded drapery, which, having in
itself an artistic effect, shall change the barrier into beauty. Nothing is better
understood than that no square angles should divide a drawing-room, and
the curtain is more graceful than any arch or architraves for that purpose.
The following sketch may convey some idea of an effect which has been
secured in Townsend House, Titchfield Terrace, residence of the
distinguished artist Mr. Alma Tadema; though the impression can be but
feeble, on account of the exquisite use he has made of the colors, which
must be left to the reader’s imagination, with a warning that they are as
quiet as they are rich.
DRAWING-ROOM IN TOWNSEND HOUSE.

The question as to the best color for a wall, one of whose chief objects is
to show off framed pictures, is a vexed one. Messrs. Christie & Co., the
famous art auctioneers, have their rooms hung with dark green baize from
floor to sky-light, and certainly the result justifies their experience; but I
think any one who enters the hall of Sir F. Leighton, P.R.A., will see that
there may be a more effective wall-color to set off pictures than green, not
to speak of certain other effects of the latter which really put it out of the
question. It is difficult to say just what the color in Sir Frederick Leighton’s
hall is. It is a sombre red, which at one moment seems to be toned in the
direction of maroon, and at another in the direction of brown. It has been
made by a very fine mingling of pigments; but the general result has been to
convince me that there can be no better wall for showing off pictures,
especially in a hall with a good deal of light, than this unobtrusive reddish-
brown. I remember that when the Boston Theatre was first opened a wall of
somewhat similar color added greatly to the brilliancy of the scenery. But
there are many eyes to which this would not be a pleasing color or shade
even for a hall—it would hardly be beautiful in a purely domestic room—
and such will do well to try some of the many beautiful shades of olive or
sage-gray. Mr. W. J. Hennessy, the eminent American artist, made his house
in Douro Place, before he left it for the old château in Calvados, remarkably
charming by a careful use of such shades throughout. His quiet rooms were
restful as they were pervaded by refinement, and each frame on the walls
had a perfect relief, each picture a full glow.
The house of Sir Frederick Leighton, in Holland Park Road, is, in the
first place, a remarkably interesting house architecturally, and shows plainly
that Mr. George Aitchison has not only been in classic regions, but imbibed
their spirit. In this house, which he has built for the artist who beyond all
Academicians displays the most sensitive sympathies with various styles,
there is nothing foreign, and yet the whole feeling about it is classic. The
little balcony would have done for the sweet lady of Verona, and yet there is
as much of Shakspeare’s England in the substantial arches at the base of the
wall. It is rare, indeed, that any house built in England in recent times has
about it as much elegance and simplicity as this. Entering the house, the
impression conveyed at once is that it is the residence of an artist. He has
employed decorators, indeed, but he has watched over them, and he has

secured thereby this—that there is nothing ugly in his house. A great merit!
Many rooms upon which large sums have been lavished have something
lugged in that makes all the rest appear vulgar or pretentious. It is a large
part of the art of decoration to know what not to have in a house. In this
house is also realized the truth of the old French saying, “Peu de moyens,
beaucoup d’effet.” For example, the doors are of deal, painted with a rich
black paint; on each jamb there is at the bottom a spreading golden root,
from which runs a stem with leaves; half-way up the stem ends in the
profile of a sunflower in gold; another stem then passes up, ending in the
full face of the sunflower, which at once crowns the foliation of the jambs,
and makes a noble ornament for the capping of the door, which also has a
central golden ornament. This black door, with its black jambs and its
golden flowers, varied on other doors to other conventional forms, has an
exceedingly rich effect. The hall also bears witness, notwithstanding its
mosaic floors, marquet chairs, and the grand old stairway that runs with it to
the top of the house, that the wealth of knowledge and experience has done
more for it than riches of a more prosaic kind, though there has been no
stint of the latter. One thing in the hall struck me as especially ingenious,
and at the same time beautiful. Just opposite to the entrance from the
vestibule into the hall the stair begins to ascend beyond large white pillars.
Now, between the first and second of these pillars there is a little balcony,
about as high above the floor as one’s head. On examination it is found that
this balcony is made out of an inlaid cabinet chest, the top and farther side
of which have been removed to make way for cushions. These cushions
have been finely embroidered with various delicate tints upon a lustrous
olive satin by Miss Jekyl, and the little balcony, with pretty ornaments on it
here and there, becomes a main feature of the hall. There are several other
pieces of Miss Jekyl’s work in the house, one of the most beautiful being a
red table-cloth in the dining-room, upon which she has worked four figures
of pots, whose flowers converge toward the centre. This cover is
appropriate to the red color which prevails in the dining-room—a color
which I do not much like in a dining-room, though here it well sets off the
large ebonized and inlaid sideboard, which is adorned with a great deal of
the finest Rhodian porcelain. Sir Frederick Leighton on returning from a
visit to the East brought back a whole treasury of china and tiles; and he has
also brought a large number of beautiful Persian tiles, with which he has
made a little interior rotunda and dome which is a marvel of beauty. A

sentence of the Koran runs along the cornice; stained glass throws a rich
light through the room; a fountain plays in the centre. Mr. Dillon, an artist,
has for some time had a studio in which every article came from Egypt,
even to the inscription from the Koran (Sura 91) which makes its frieze—
“By the brightness of the sun when he shineth,
By the moon when she followeth him,” etc.
Sir Frederick Leighton’s chief room is his studio; it covers more than
half of the whole area of the top floor of the house. The walls are hung with
stuffs from many countries—tapestries, rugs, ancient Japanese silks—which
fall from the cornice to the floor. There are some fine ebonized bookcases
and cabinets, designed by Mr. Aitchison and Sir Frederick together. The
roof is arranged with sky-lights and sliding curtains of various descriptions,
so that there is no kind of light or shade whatever that the artist is not able
to bring upon his work. The drawing-room has a white coffered and tinted
ceiling, and neat mouldings above the bay-window gather round a fine oil-
picture, by Eugene Delacroix, fixed in the ceiling. It is beautiful, but I could
not help feeling that some mural painting by another artist might well be
substituted, and the Delacroix placed “on the line.” There is suspended a
very rich central candelabrum of Venetian glass in many colors. The walls
are hung with cigar-tinted cloth, with modified fleur-de-lis spots, beneath
which a floor of ash-blue is disclosed for the width of a yard between the
wall and the bright Persian carpet.
A GRATE OF ONE HUNDRED YEARS
AGO.

Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com