This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
800 East 96th Street, Indianapolis, Indiana, 46240 USA
Sams Teach Yourself Ajax in 10 Minutes
ACQUISITIONS EDITOR
Copyright 2006 by Sams Publishing
Damon Jordan
All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein. International Standard Book Number: 0-672-32868-2 Library of Congress Catalog Card Number: 2005934928 Printed in the United States of America First Printing: April 2006 09 08 07 06 4 3 2 1
Linda Harrison
DEVELOPMENT EDITOR
MANAGING EDITOR Charlotte Clapp
PROJECT EDITOR Seth Kerney
COPY EDITOR Geneil Breeze
INDEXER Ken Johnson
PROOFREADER Leslie Joseph
TECHNICAL EDITOR
Trademarks
Bill Bercik
All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.
PUBLISHING COORDINATOR
Warning and Disclaimer
Dan Scherf
Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis. The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book or from the use of the CD or programs accompanying it.
INTERIOR DESIGNER
Bulk Sales Sams Publishing offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information, please contact U.S. Corporate and Government Sales 1-800-382-3419 [email protected] For sales outside of the U.S., please contact International Sales [email protected]
Vanessa Evans
MULTIMEDIA DEVELOPER
Gary Adair
COVER DESIGNER Aren Howell
PAGE LAYOUT TnT Design
Contents Introduction
1
About This Book..................................................................................1 What Is Ajax? ......................................................................................1 Who This Book Is For ........................................................................3 What Do I Need To Use This Book? ..................................................3 Conventions Used in This Book ..........................................................3 Online Resources and Errata ..............................................................4
PART I 1
A Refresher on Web Technologies
Anatomy of a Website
5
A Short History of the Web ................................................................5 Workings of the World Wide Web ......................................................6 Summary ............................................................................................12
2
Writing Web Pages in HTML
13
Introducing HTML ............................................................................13 Elements of an HTML Page ..............................................................16 A More Advanced HTML Page ........................................................21 Some Useful HTML Tags..................................................................23 Cascading Style Sheets in Two Minutes............................................25 Summary ............................................................................................26
3
Sending Requests Using HTTP
27
Introducing HTTP..............................................................................27 The HTTP Request and Response ....................................................28 HTML Forms ....................................................................................31 Summary ............................................................................................35
iv
Sams Teach Yourself Ajax in Ten Minutes
4
Client-Side Coding Using JavaScript
36
About JavaScript ................................................................................36 In at the Deep End ............................................................................38 Manipulating Data in JavaScript........................................................49 Summary ............................................................................................52
5
Server-Side Programming in PHP
53
Introducing PHP ................................................................................53 Embedding PHP in HTML Pages......................................................54 Variables in PHP ................................................................................56 Controlling Program Flow ................................................................58 Summary ............................................................................................60
6
A Brief Introduction to XML
61
Introducing XML ..............................................................................61 XML Basics ......................................................................................62 JavaScript and XML ..........................................................................66 The Document Object Model (DOM) ..............................................67 Summary ............................................................................................69
PART II 7
Introducing Ajax
Anatomy of an Ajax Application
70
The Need for Ajax ............................................................................70 Introducing Ajax ................................................................................73 The Constituent Parts of Ajax............................................................75 Putting It All Together ......................................................................78 Summary ............................................................................................79
8
The XMLHTTPRequest Object
80
More About JavaScript Objects ........................................................80 Introducing XMLHTTPRequest..............................................................82 Creating the XMLHTTPRequest Object ................................................83 Summary ............................................................................................90
Contents
9
Talking with the Server
v
91
Sending the Server Request ..............................................................91 Monitoring Server Status ..................................................................97 The Callback Function ......................................................................99 Summary ..........................................................................................101
10
Using the Returned Data
102
The responseText and responseXML Properties..............................102 Another Useful JavaScript DOM Property......................................107 Parsing responseXML ........................................................................108 Providing User Feedback ................................................................109 Summary ..........................................................................................111
11
Our First Ajax Application
112
Constructing the Ajax Application ..................................................112 The HTML Document ....................................................................112 Adding JavaScript ............................................................................114 Putting It All Together ....................................................................118 Summary ..........................................................................................122
PART III 12
More Complex Ajax Technologies
Returning Data as Text
123
Getting More from the responseText Property ..............................123 Summary ..........................................................................................130
13
AHAH—Asynchronous HTML and HTTP
131
Introducing AHAH ..........................................................................131 Creating a Small Library for AHAH ..............................................132 Using myAHAHlib.js ......................................................................135 Summary ..........................................................................................141
vi
Sams Teach Yourself Ajax in Ten Minutes
14
Returning Data as XML
142
Adding the “x” to Ajax ....................................................................142 The responseXML Property ..............................................................143 Project—An RSS Headline Reader ................................................148 Summary ..........................................................................................156
15
Web Services and the REST Protocol
157
Introduction to Web Services ..........................................................157 REST—Representational State Transfer ........................................158 Using REST in Practice ..................................................................160 REST and Ajax ................................................................................165 Summary ..........................................................................................165
16
Web Services Using SOAP
166
Introducing SOAP (Simple Object Access Protocol) ......................166 The SOAP Protocol ........................................................................167 Using Ajax and SOAP ....................................................................170 Reviewing SOAP and REST ..........................................................172 Summary ..........................................................................................172
17
A JavaScript Library for Ajax
173
An Ajax Library ..............................................................................173 Reviewing myAHAHlib.js ..............................................................174 Implementing Our Library ..............................................................175 Using the Library ............................................................................179 Extending the Library ......................................................................182 Summary ..........................................................................................183
18
Ajax “Gotchas”
184
Common Ajax Errors ......................................................................184 The Back Button ..............................................................................184 Bookmarking and Links ..................................................................185 Telling the User That Something Is Happening ..............................186 Making Ajax Degrade Elegantly ....................................................186 Dealing with Search Engine Spiders ..............................................187 Pointing Out Active Page Elements ................................................188 Don’t Use Ajax Where It’s Inappropriate........................................189 Security ............................................................................................189
Contents
Test Code Across Multiple Platforms..............................................189 Ajax Won’t Cure a Bad Design ......................................................190 Some Programming Gotchas ..........................................................190 Summary ..........................................................................................192
About the Author Phil Ballard graduated in 1980 with an honors degree in electronics from the University of Leeds, England. Following an early career as a research scientist with a major multinational, Phil spent a few years in commercial and managerial roles within the high technology sector, later working full time as a software engineering consultant. Operating as “The Mouse Whisperer” (http://www.mousewhisperer. co.uk), Phil has spent recent years involved solely in website and intranet design and development for an international portfolio of clients. Another of his websites, http://www.crackajax.net, is home to an active and fastgrowing Ajax programming community. Phil is currently based in southeast England. In his spare time, he still plays bass guitar in rock bands, despite being easily old enough to know better.
Dedication To Sue, for her endless patience and support during the writing of this book—and at all other times, too.
Acknowledgments I would like to offer my sincere thanks for the team at Sams Publishing, especially Linda Harrison, Shelley Johnston, Damon Jordan, Seth Kerney, Geneil Breeze, and Andrea Bledsoe. Bill Bercik deserves special thanks, not only for his excellent work as technical editor, but also for his article at http://www.webpasties.com that inspired my interest in Ajax in the first place. I would also like to express my gratitude to the countless individuals who have shared their knowledge and skill by writing open source software, Internet articles, and tutorials. Without their contributions, this book, and a great deal else, would not have been possible.
We Want to Hear from You! As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we’re doing right, what we could do better, what areas you’d like to see us publish in, and any other words of wisdom you’re willing to pass our way. You can email or write me directly to let me know what you did or didn’t like about this book—as well as what we can do to make our books stronger. Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message. When you write, please be sure to include this book’s title and author as well as your name and phone or email address. I will carefully review your comments and share them with the author and editors who worked on the book. Email:
Mark Taber Associate Publisher Sams Publishing 800 East 96th Street Indianapolis, IN 46240 USA
Reader Services Visit our website and register this book at www.samspublishing.com/ register for convenient access to any updates, downloads, or errata that might be available for this book.
Introduction Ajax is stirring up high levels of interest in the Internet development community. Ajax allows developers to provide visitors to their websites slick, intuitive user interfaces somewhat like those of desktop applications instead of using the traditional page-based web paradigm. Based on well-known and understood technologies such as JavaScript and XML, Ajax is easily learned by those familiar with the mainstream web design technologies and does not require users to have any browser plugins or other special software.
About This Book Part of the Sams Publishing Teach Yourself in 10 Minutes series, this book aims to teach the basics of building Ajax applications for the Internet. Divided into bite-sized lessons, each designed to take no more than about 10 minutes to complete, this volume offers • A review of the technologies on which the World Wide Web is based • Basic tutorials/refreshers in HTML, JavaScript, PHP, and XML • An understanding of the architecture of Ajax applications • Example Ajax coding projects After completing all the lessons you’ll be equipped to write and understand basic Ajax applications, including all necessary client- and serverside programming.
What Is Ajax? Ajax stands for Asynchronous Javascript And XML. Although strictly speaking Ajax itself is not a technology, it mixes well-known programming techniques in an uncommon way to enable web developers to build
2
Sams Teach Yourself AJAX in Ten Minutes
Internet applications with much more appealing user interfaces than those to which we have become accustomed. When using popular desktop applications, we expect the results of our work to be made available immediately, without fuss, and without us having to wait for the whole screen to be redrawn by the program. While using a spreadsheet such as Excel, for instance, we expect the changes we make in one cell to propagate immediately through the neighboring cells while we continue to type, scroll the page, or use the mouse. Unfortunately, this sort of interaction has seldom been available to users of web-based applications. Much more common is the experience of entering data into form fields, clicking on a button or link, and then sitting back while the page slowly reloads to exhibit the results of the request. In addition, we often find that the majority of the reloaded page consists of elements that are identical to those of the previous page and that have therefore been reloaded unnecessarily; background images, logos, and menus are frequent offenders. Ajax promises us a solution to this problem. By working as an extra layer between the user’s browser and the web server, Ajax handles server communications in the background, submitting server requests and processing the returned data. The results may then be integrated seamlessly into the page being viewed, without that page needing to be refreshed or a new one loaded. In Ajax applications, such server requests are not necessarily synchronized with user actions such as clicking on buttons or links. A well-written Ajax application may already have asked of the server, and received, the data required by the user—perhaps before the user even knew she wanted it. This is the meaning of the asynchronous part of the Ajax acronym. The parts of an Ajax application that happen “under the hood” of the user’s browser, such as sending server queries and dealing with the returned data, are written in JavaScript, and XML is an increasingly popular means of coding and transferring formatted information used by Ajax to efficiently transfer data between server and client. We’ll look at all these techniques, and how they can be made to work together, as we work through the lessons.
Introduction
Who This Book Is For This volume is aimed primarily at web developers seeking to build better interfaces for the users of their web applications and programmers from desktop environments looking to transfer their applications to the Internet. It also proves useful to web designers eager to learn how the latest techniques can offer new outlets for their creativity. Although the nature of Ajax applications means that they require some programming, all the required technologies are explained from first principles within the book, so even those with little or no programming experience should be able to follow the lessons without a great deal of difficulty.
What Do I Need To Use This Book? The main requirement is to have an interest in exploring how people and computers might work better together. Although some programming experience, especially in JavaScript, will certainly be useful it is by no means mandatory because there are introductory tutorials in all the required technologies. To try out the program code for yourself you need access to a web server and the means to upload files to it (for example, via File Transfer Protocol, usually called FTP). Make sure that your web host allows you to use PHP scripts on the server, though the majority do these days. To write and edit program code you need a suitable text editor. Windows Notepad does the job perfectly well, though some specialized programmers’ editors offer additional useful facilities such as line numbering and syntax highlighting. The appendix contains details of some excellent examples that may be downloaded and used free of charge.
Conventions Used in This Book In addition to the main text of each lesson, you will find a number of boxes labeled as Tips, Notes, and Cautions.
3
4
Sams Teach Yourself AJAX in Ten Minutes
Tip Tips offer useful shortcuts or easier ways to achieve something.
Note Notes are snippets of extra information relevant to the current theme of the text.
Caution Cautions detail traps that may catch the unwary and advise how to avoid them.
Online Resources and Errata Visit the Sams Publishing website at www.samspublishing.com where you can download the example code and obtain further information and details of errata.
LESSON 1
Anatomy of a Website We have a lot of ground to cover in this book, so let’s get to it. We’ll begin by reviewing in this lesson what the World Wide Web is and where it came from. Afterward we’ll take a look at some of the major components that make it work.
A Short History of the Web In the late 1950s, the U.S. government formed the Advanced Research Projects Agency (ARPA). This was largely a response to the Russian success in launching the Sputnik satellite and employed some of the country’s top scientific intellects in research work with U.S. military applications. During the 1960s, the agency created a decentralized computer network known as ARPAnet. This embryonic network initially linked four computers located at the University of California at Los Angeles, Stanford Research Institute, the University of California at Santa Barbara, and the University of Utah, with more nodes added in the early 1970s. The network had initially been designed using the then-new technology of packet switching and was intended as a communication system that would remain functional even if some nodes should be destroyed by a nuclear attack. Email was implemented in 1972, closely followed by the telnet protocol for logging on to remote computers and the File Transfer Protocol (FTP), enabling file transfer between computers. This developing network was enhanced further in subsequent years with improvements to many facets of its protocols and tools. However, it was not until 1989 when Tim Berners-Lee and his colleagues at the European
6
Lesson 1
particle physics laboratory CERN (Conseil Européen pour le Recherche Nucléaire) proposed the concept of linking documents with hypertext that the now familiar World Wide Web began to take shape. The year 1993 saw the introduction of Mosaic, the first graphical web browser and forerunner of the famous Netscape Navigator. The use of hypertext pages and hyperlinks helped to define the pagebased interface model that we still regard as the norm for web applications today.
Workings of the World Wide Web The World Wide Web operates using a client/server networking principle. When you enter the URL (the web address) of a web page into your browser and click on Go, you ask the browser to make an HTTP request of the particular computer having that address. On receiving this request, that computer returns (“serves”) the required page to you in a form that your browser can interpret and display. Figure 1.1 illustrates this relationship. In the case of the Internet, of course, the server and client computers may be located anywhere in the world.
Client
Client
HTTP Request
Server Client
FIGURE 1.1
HTML Response
Client
How web servers and clients (browsers) interact.
Lesson 3, “Sending Requests Using the HTTP Protocol,” discusses the nitty-gritty of HTTP requests in more detail. For now, suffice to say that
Anatomy of a Website
your HTTP request contains several pieces of information needed so that your page may be correctly identified and served to you, including the following: • The domain at which the page is stored (for example, mydomain.com) • The name of the page (This is the name of a file in the web server’s file system—for example, mypage.html.) • The names and values of any parameters that you want to send with your request
What Is a Web Page? Anyone with some experience using the World Wide Web will be familiar with the term web page. The traditional user interface for websites involves the visitor navigating among a series of connected pages each containing text, images, and so forth, much like the pages of a magazine. Generally, each web page is actually a separate file on the server. The collection of individual pages constituting a website is managed by a program called a web server.
Web Servers A web server is a program that interprets HTTP requests and delivers the appropriate web page in a form that your browser can understand. Many examples are available, most running under either UNIX/Linux operating systems or under some version of Microsoft Windows.
Caution The term web server is often used in popular speech to refer to both the web server program— such as Apache—and the computer on which it runs.
Perhaps the best-known server application is the Apache Web Server from the Apache Software Foundation (http://www.apache.org), an open source project used to serve millions of websites around the world (see Figure 1.2).
7
8
Lesson 1
FIGURE 1.2 The Apache Software Foundation home page at http://www.apache.org/ displayed in Internet Explorer.
Another example is Microsoft’s IIS (Internet Information Services), often used on host computers running the Microsoft Windows operating system.
Note Not all Windows-based web hosts use IIS. Various other web servers are available for Windows, including a version of the popular Apache Web Server.
Server-Side Programming Server-side programs, scripts, or languages, refer to programs that run on the server computer. Many languages and tools are available for serverside programming, including PHP, Java, and ASP (the latter being available only on servers running the Microsoft Windows operating system). Sophisticated server setups often also include databases of information that can be addressed by server-side scripts.
Anatomy of a Website
Note Server-side programming in this book is carried out using the popular PHP scripting language, which is flexible, is easy to use, and can be run on nearly all servers. Ajax, however, can function equally well with any server-side scripting language.
The purposes of such scripts are many and various. In general, however, they all are designed to preprocess a web page before it is returned to you. By this we mean that some or all of the page content will have been modified to suit the context of your request—perhaps to display train times to a particular destination and on a specific date, or to show only those products from a catalog that match your stated hobbies and interests. In this way server-side scripting allows web pages to be served with rich and varied content that would be beyond the scope of any design using only static pages—that is, pages with fixed content.
Web Browsers A web browser is a program on a web surfer’s computer that is used to interpret and display web pages. The first graphical web browser, Mosaic, eventually developed into the famous range of browsers produced by Netscape.
Note By graphical web browser we mean one that can display not only the text elements of an HTML document but also images and colors. Typically, such browsers have a point-and-click interface using a mouse or similar pointing device. There also exist text-based web browsers, the best known of which is Lynx (http://lynx.browser.org/), which display HTML pages on character-based displays such as terminals, terminal emulators, and operating systems with command-line interfaces such as DOS.
9
10
Lesson 1
The Netscape series of browsers, once the most successful available, were eventually joined by Microsoft’s Internet Explorer offering, which subsequently went on to dominate the market. Recent competitive efforts, though, have introduced a wide range of competing browser products including Opera, Safari, Konqueror, and especially Mozilla’s Firefox, an open source web browser that has recently gained an enthusiastic following (see Figure 1.3). Browsers are readily available for many computer operating systems, including the various versions of Microsoft Windows, UNIX/Linux, and Macintosh, as well as for other computing devices ranging from mobile telephones to PDAs (Personal Digital Assistants) and pocket computers.
FIGURE 1.3 The Firefox browser from Mozilla.org browsing the Firefox Project home page.
Anatomy of a Website
Client-Side Programming We have already discussed how server scripts can improve your web experience by offering pages that contain rich and varied content created at the server and inserted into the page before it is sent to you. Client-side programming, on the other hand, happens not at the server but right inside the user’s browser after the page has been received. Such scripts allow you to carry out many tasks relating to the data in the received page, including performing calculations, changing display colors and styles, checking the validity of user input, and much more. Nearly all browsers support some version or other of a client-side scripting language called JavaScript, which is an integral part of Ajax and is the language we’ll be using in this book for client-side programming.
DNS—The Domain Name Service Every computer connected to the Internet has a unique numerical address (called an IP address) assigned to it. However, when you want to view a particular website in your browser, you don’t generally want to type in a series of numbers—you want to use the domain name of the site in question. After all, it’s much easier to remember www.somedomain.com than something like 198.105.232.4. When you request a web page by its domain name, your Internet service provider submits that domain name to a DNS server, which tries to look up the database entry associated with the name and obtain the corresponding IP address. If it’s successful, you are connected to the site; otherwise, you receive an error. The many DNS servers around the Internet are connected together into a network that constantly updates itself as changes are made. When DNS information for a website changes, the revised address information is propagated throughout the DNS servers of the entire Internet, typically within about 24 hours.
11
12
Lesson 1
Summary In Lesson 1 we discussed the history and development of the Internet and reviewed the functions of some of its major components including web servers and web browsers. We also considered the page-based nature of the traditional website user interface and had a brief look at what server- and client-side scripting can achieve to improve users’ web surfing experience.
LESSON 2
Writing Web Pages in HTML In this lesson we introduce HTML, the markup language behind virtually every page of the World Wide Web. A sound knowledge of HTML provides an excellent foundation for the Ajax applications discussed in later lessons.
Introducing HTML It wouldn’t be appropriate to try to give an exhaustive account of HTML (Hypertext Markup Language)—or, indeed, any of the other component technologies of Ajax—within this book. Instead we’ll review the fundamental principles and give some code examples to illustrate them, paying particular attention to the subjects that will become relevant when we start to develop Ajax applications.
Tip If you want to explore HTML in greater detail, Sams Publishing offers a number of titles that will help you, including Sams Teach Yourself HTML 4 in 24 Hours by Dick Oliver.
What Is HTML? The World Wide Web is constructed from many millions of individual pages, and those pages are, in general, written in Hypertext Markup Language, better known as HTML. That name gives away a lot of information about the nature of HTML. We use it to mark up our text documents so that web browsers know how to display them and to define hypertext links within them to provide navigation within or between them.
14
Lesson 2
Anyone who (like me) can remember the old pre-WYSIWYG word processing programs will already be familiar with text markup. Most of these old applications required that special characters be placed at the beginning and end of sections of text that you wanted to be displayed as (for instance) bold, italic, or underlined text.
What Tools Are Needed to Write HTML? Because the elements used in HTML markup employ only ordinary keyboard characters, all you really need is a good text editor to construct HTML pages. Many are available, and most operating systems have at least one such program already installed. If you’re using some version of Windows, for example, the built-in Notepad application works just fine.
Tip Although Notepad is a perfectly serviceable text editor, many so-called programmers’ editors are available offering useful additional functions such as line numbering and syntax highlighting. Many of these are under open source licences and can be downloaded and used at no cost. It is well worth considering using such an editor, especially for larger or more complex programming tasks.
Caution Although text editors are ideal for writing program code, the use of word processing software can cause problems due to unwanted markup and other symbols that such programs often embed in the output code. If you choose to use a word processor, make sure that it is capable of saving files as plain ASCII text.
Our First HTML Document Let’s jump right in and create a simple HTML document. Open Notepad (or whatever editor you’ve chosen to use) and enter the text shown in Listing 2.1. The HTML markup elements (often referred to as tags) are the character strings enclosed by < and >.
Writing Web Pages in HTML
LISTING 2.1
testpage.html
A Simple HTML Document My HTML Page Welcome to my first page written in HTML. This is simply a text document with HTML markup to show some words in bold and some other words in italics.
Now save the document somewhere on your computer, giving it the name testpage.html. If you now load that page into your favorite browser, such as Internet Explorer or Firefox, you should see something like the window displayed in Figure 2.1.
FIGURE 2.1
Our test document displayed in Internet Explorer.
15
16
Lesson 2
Elements of an HTML Page Let’s look at Listing 2.1 in a little more detail. The first element on the page is known as the DOCTYPE element. Its purpose is to notify the browser of the “flavor” of HTML used in the document. The DOCTYPE element used throughout this book refers to HTML 4.0 Transitional, a fairly forgiving version of the HTML specification that allows the use of some earlier markup styles and structures in addition to the latest HTML 4.0 specifications. The DOCTYPE element must always occur right at the beginning of the HTML document. Next, note that the remainder of the document is enclosed by the elements at the start of the page and at the end. These tags notify the browser that what lies between should be interpreted and displayed as an HTML document.
Caution Although many modern browsers correctly display HTML without these tags, it is bad practice to omit them. Even if the page is shown correctly on your own PC, you have no idea what operating system and browser a visitor may be using—he may not be so lucky.
The document within these outer tags is split into two further sections. The first is enclosed in and tags, and the second is contained between and . Essentially, the document’s head section is used to store information about the document that is not to be displayed in the browser window, whereas the body of the document contains text to be interpreted and displayed to the user via the browser window.
The of the Document From Listing 2.1 we can see that the head section of our simple HTML document contains only one line—the words A Simple HTML Document enclosed in and tags.
Writing Web Pages in HTML
Remember that the head section contains information that is not to be displayed in the browser window. This is not, then, the title displayed at the top of our page text, as you can confirm by looking again at Figure 2.1. Neither does the document title refer to the filename of the document, which in this case is testpage.html. In fact, the document title fulfils a number of functions, among them: • Search engines often use the page title (among other factors) to help them decide what a page is about. • When you bookmark a page, it is generally saved by default as the document title. • Most browsers, when minimized, display the title of the current document on their icon or taskbar button. It’s important, therefore, to choose a meaningful and descriptive title for each page that you create. Many other element types are used in the head section of a document, including link, meta, and script elements. Although we don’t give an account of them here, they are described throughout the book as they occur.
The Document Referring again to Listing 2.1, we can clearly see that the content of the document’s body section is made up of the text we want to display on the page, plus some tags that help us to define how that text should look. To define that certain words should appear in bold type, for example, we enclose those words in and tags. Similarly, to convert certain words into an italic typeface, we can use the and tags. The heading, My HTML Page, is enclosed between and tags. These indicate that we intend the enclosed text to be a heading. HTML allows for six levels of headings, from h1 (the most prominent) to h6. You can use any of the intermediate values h2, h3, h4, and h5 to display pages having various levels of subtitles, for instance corresponding to chapter, section, and paragraph headings. Anything displayed within header tags is displayed on a line by itself.
17
18
Lesson 2
All the tags discussed so far have been containers—that is, they consist of opening and closing tags between which you place the text that you want these tags to act upon. Some elements, however, are not containers but can be used alone. Listing 2.1 shows one such element: the tag, which signifies a line break. Another example is (a horizontal line).
Tip If you want to write in the body section of the HTML page but don’t want it to be interpreted by the browser and therefore displayed on the screen, you may do so by writing it as a comment. HTML comments start with the character string as in this example:
Adding Attributes to HTML Elements Occasionally there is a need to specify exactly how a markup tag should behave. In such cases you can add (usually within the opening tag) parameter and value pairs, known as attributes, to change the behavior of the element: … page content goes here …
In this example, the behavior of the tag has been modified by adjusting its BGCOLOR (background color) property to a light gray. Figure 2.2 shows the effect this has if applied to our file testpage.html:
Writing Web Pages in HTML
FIGURE 2.2
Our test page with the body color changed to gray.
Tip Color values in HTML are coded using a hexadecimal system. Each color value is made up from three component values, corresponding to red, green, and blue. Each of the color values can range from hex 00 to hex ff (zero to 255 in decimal notation). The three hex numbers are concatenated into a string prefixed with a hash character #. The color value #000000 therefore corresponds to black, and #ffffff to pure white.
19
20
Lesson 2
Images Images can be inserted in our page by means of the tag. In this case we specify the source file of the image as a parameter by using the src attribute. Other aspects of the image display that we can alter this way include the borders, width, and height of the image:
Border width, image width, and image height are in numbers of pixels (the “dots” formed by individual picture elements on the screen).
Tip A further useful attribute for images is alt, which is an abbreviation of alternative text. This specifies a short description of the image that will be offered to users whose browsers cannot, or are configured not to, display images. Alternative text can also be important in making your website accessible to those with visual impairment and other disabilities:
Tables Often you want to display information in tabular format, and HTML has a set of elements designed specifically for this purpose:
Column Header 1
Column Header 2
Data Cell 1
Data Cell 2
Data Cell 3
Data Cell 4
The
and
tags contain a nested hierarchy of other tags, including
and
, which define individual table rows;
and
, which indicate cells in the table’s header; and
and
, which contain individual cells of table data. Look ahead to Figure 2.3 to see an example of how a table looks when displayed in a browser window.
Writing Web Pages in HTML
Hyperlinks Hypertext links (hyperlinks) are fundamental to the operation of HTML. By clicking on a hyperlink, you can navigate to a new location, be that to another point on the current page or to some point on a different page on another website entirely. Links are contained within an , or anchor tag, a container tag that encloses the content that will become the link. The destination of the link is passed to this tag as a parameter href: Here is my hyperlink
Clicking on the words my hyperlink in the above example results in the browser requesting the page newpage.html.
Tip A hyperlink can contain images as well as, or instead of, text. Look at this example:
Here, a user can click on the image picfile.gif to navigate to newpage.html.
A More Advanced HTML Page Let’s revisit our testpage.html and add some extra elements. Listing 2.2 shows seville.html, developed from our original HTML page but with different content in the section of the document. Figure 2.3 shows how the page looks when displayed, this time in Mozilla Firefox. Now we have applied a background tint to the body area of the document. The content of the body area has been centered on the page, and that content now includes an image (which we’ve given a two-pixel-wide border), a heading and a subheading, a simple table, and some text.
LISTING 2.2
seville.html
continues
21
22
Lesson 2
LISTING 2.2
Continued
A Simple HTML Document Guide to Seville A brief guide to the attractions
Attraction
Description
Cathedral
Dating back to the 15th century
Alcazar
The medieval Islamic palace
Enjoy your stay in beautiful Seville.
Let’s take a closer look at some of the code. First, we used the BGCOLOR property of the tag to provide the overall background tint for the page:
Everything in the body area is contained between the tag (immediately after the body tag) and its partner , immediately before the closing body tag. This ensures that all of our content is centered on the page. The main heading is enclosed in … tags as previously, but is now followed by a subheading using … tags to provide a slightly smaller font size. By using the border property in our opening
tag, we set a border width of two pixels for the table:
Writing Web Pages in HTML
Meanwhile we darkened the background of the table’s header cells slightly by using the BGCOLOR property of the
elements:
Attraction
FIGURE 2.3
seville.html shown in Mozilla Firefox.
Some Useful HTML Tags Table 2.1 lists some of the more popular HTML tags.
TABLE 2.1
Some Common HTML Markup Elements
Document Tags ..
The entire document
..
Document head continues
23
24
Lesson 2
TABLE 2.1
Continued
Document Tags ..
Document body
..
Document title
Style Tags ..
Hyperlink
..
Bold text
..
Emphasized text
..
Changed font
..
Italic text
..
Small text
..
Table
..
Table row
..
Cell in table header
..
Cell in table body
..
Bulleted list
..
Ordered (numbered) list
..
List item in bulleted or ordered list
Tip The World Wide Web Consortium is responsible for administering the definitions of HTML, HTTP, XML, and many other web technologies. Its website is at http://www.w3.org/.
Writing Web Pages in HTML
Cascading Style Sheets in Two Minutes The preceding approach to styling web pages has a few downsides. First, you need to explicitly state the attributes of each page element. When you want to change the look of the page, you need to go through the source code line by line and change every instance of every attribute. This may be okay with a few simple pages, but as the amount of content increases, the pages become more difficult to maintain. Additionally, the attributes applied to HTML elements allow only limited scope for you to adjust how they are displayed. Wouldn’t it be better to make one change to the code and have that change applied to all HTML elements of a given type? As I’m sure you’ve already guessed, you can. To achieve this goal you use styles. Styles may be embedded within your HTML document by using style tags in the head of the document: … style definition statements …
Alternatively, they may be linked from an external file, using a link element, once again placed in the head section of the document:
Tip You can even define styles on-the-fly. These are known as inline styles and can be applied to individual HTML elements. Taking the body tag of Listing 2.2 as an example:
You could achieve the same effect using an inline style:
25
26
Lesson 2
Setting Style Sheet Rules Style sheets allow you to set styling rules for the various HTML elements. A rule has two components: the selector, which identifies which HTML tag the rule should affect, and the declaration, which contains your styling rule. The following example defines a style for the paragraph element,
: P {color: #333333}
This example determines that any text enclosed in paragraph tags
…
should be displayed using dark gray text. You may also specify more than one rule for each tag. Suppose that, in addition to gray text, you want all text in the paragraph element to be displayed in italics: P {color: #333333; font-style: italic}
A style sheet can contain as many such rules as you require. You may also apply a declaration to more than one tag at once, by separating the tag selectors with commas. The following rule determines that all h1, h2, and h3 headings appear in blue text: H1, H2, H3 {color: blue}
Summary This lesson discussed the basics of web page layout using Hypertext Markup Language, including the structure of HTML documents, examples of HTML page elements, and page styling using both element attributes and cascading style sheets.
LESSON 3
Sending Requests Using HTTP Various protocols are used for communication over the World Wide Web, perhaps the most important being HTTP, the protocol that is also fundamental to Ajax applications. This lesson introduces the HTTP protocol and shows how it is used to request and receive information.
Introducing HTTP HTTP or Hypertext Transfer Protocol is the main protocol of the World Wide Web. When you request a web page by typing its address into your web browser, that request is sent using HTTP. The browser is an HTTP client, and the web page server is (unsurprisingly) an HTTP server. In essence, HTTP defines a set of rules regarding how messages and other data should be formatted and exchanged between servers and browsers.
Why Do I Need To Know About This? Ajax sends server requests using the HTTP protocol. It’s important to recognize the different types of HTTP requests and the responses that the server may return. Ajax applications need to construct HTTP requests to query the server and will base decisions about what to do next on the content of HTTP responses from the server.
What Is (and Isn’t) Covered in This Lesson It would be possible to fill the whole book with information on the HTTP protocol, but here we simply discuss it in terms of its roles in requesting web pages and passing information between them.
28
Lesson 3
In this lesson you’ll look at the construction of HTTP requests and responses and see how HTML forms use such requests to transfer data between web pages.
Tip For a detailed account of HTTP, see Sams Publishing’s HTTP Developer’s Handbook by Chris Shiflett.
The HTTP Request and Response The HTTP protocol can be likened to a conversation based on a series of questions and answers, which we refer to respectively as HTTP requests and HTTP responses. The contents of HTTP requests and responses are easy to read and understand, being near to plain English in their syntax. This section examines the structure of these requests and responses, along with a few examples of the sorts of data they may contain.
The HTTP Request After opening a connection to the intended server, the HTTP client transmits a request in the following format: • An opening line • Optionally, a number of header lines • A blank line • Optionally, a message body The opening line is generally split into three parts; the name of the method, the path to the required server resource, and the HTTP version being used. A typical opening line might read: GET /sams/testpage.html HTTP/1.0
Sending Requests Using HTTP
In this line we are telling the server that we are sending an HTTP request of type GET (explained more fully in the next section), we are sending this using HTTP version 1.0, and the server resource we require (including its local path) is /sams/testpage.html.
Note In this example the server resource we seek is on our own server, so we have quoted a relative path. It could of course be on another server elsewhere, in which case the server resource would include the full URL.
Header lines are used to send information about the request, or about the data being sent in the message body. One parameter and value pair is sent per line, the parameter and value being separated by a colon. Here’s an example: User-Agent: [name of program sending request]
For instance, Internet Explorer v5.5 offers something like the following: User-agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)
A further example of a common request header is the Accept: header, which states what sort(s) of information will be found acceptable as a response from the server: Accept: text/plain, text/html
By issuing the header in the preceding example, the request is informing the server that the sending application can accept either plain text or HTML responses (that is, it is not equipped to deal with, say, an audio or video file) .
Note
HTTP request methods include POST, GET, PUT, DELETE, and HEAD. By far the most interesting in our pursuit of Ajax are the GET and POST requests. The PUT, DELETE, and HEAD requests are not covered here.
29
30
Lesson 3
The HTTP Response In answer to such a request, the server typically issues an HTTP response, the first line of which is often referred to as the status line. In that line the server echoes the HTTP version and gives a response status code (which is a three-digit integer) and a short message known as a reason phrase. Here’s an example HTTP response: HTTP/1.0 200 OK
The response status code and reason phrase are essentially intended as machine-and human-readable versions of the same message, though the reason phrase may actually vary a little from server to server. Table 3.1 lists some examples of common status codes and reason phrases. The first digit of the status code usually gives some clue about the nature of the message: • 1**—Information • 2**—Success • 3**—Redirected • 4**—Client error • 5**—Server error
TABLE 3.1 Some Commonly Encountered HTTP Response Status Codes Status Code
Explanation
200 - OK
The request succeeded.
204 - No Content
The document contains no data.
301 - Moved Permanently
The resource has permanently moved to a different URI.
401 - Not Authorized
The request needs user authentication.
403 - Forbidden
The server has refused to fulfill the request.
404 - Not Found
The requested resource does not exist on the server.
Sending Requests Using HTTP
Status Code
Explanation
408 - Request Timeout
The client failed to send a request in the time allowed by the server.
500 - Server Error
Due to a malfunctioning script, server configuration error or similar.
Tip A detailed list of status codes is maintained by the World Wide Web Consortium, W3C, and is available at http://www.w3.org/Protocols/rfc2616/ rfc2616-sec10.html.
The response may also contain header lines each containing a header and value pair similar to those of the HTTP request but generally containing information about the server and/or the resource being returned: Server: Apache/1.3.22 Last-Modified: Fri, 24 Dec 1999 13:33:59 GMT
HTML Forms Web pages often contain fields where you can enter information. Examples include select boxes, check boxes, and fields where you can type information. Table 3.2 lists some popular HTML form tags.
TABLE 3.2
Some Common HTML Form Tags
Tag
Description
...
Container for the entire form
Data entry element; includes text, password, check box and radio button fields, and submit and reset buttons
...
Drop-down select box
...
Selectable option within select box
...
Text entry field with multiple rows
31
32
Lesson 3
After you have completed the form you are usually invited to submit it, using an appropriately labeled button or other page element. At this point, the HTML form constructs and sends an HTTP request from the user-entered data. The form can use either the GET or POST request type, as specified in the method attribute of the tag.
GET and POST Requests Occasionally you may hear it said that the difference between GET and POST requests is that GET requests are just for GETting (that is, retrieving) data, whereas POST requests can have many uses, such as uploading data, sending mail, and so on. Although there may be some merit in this rule of thumb, it’s instructive to consider the differences between these two HTTP requests in terms of how they are constructed. A GET request encodes the message it sends into a query string, which is appended to the URL of the server resource. A POST request, on the other hand, sends its message in the message body of the request. What actually happens at this point is that the entered data is encoded and sent, via an HTTP request, to the URL declared in the action attribute of the form, where the submitted data will be processed in some way. Whether the HTTP request is of type GET or POST and the URL to which the form is sent are both determined in the HTML markup of the form. Let’s look at the HTML code of a typical form: Your Surname:
This snippet of code, when embedded in a web page, produces the simple form shown in Figure 3.1.
Sending Requests Using HTTP
FIGURE 3.1
A simple HTML form.
Let’s take a look at the code, line by line. First, we begin the form by using the tag, and in this example we give the tag two attributes. The action attribute determines the URL to which the submitted form will be sent. This may be to another page on the same server and described by a relative path, or to a remote domain, as in the code behind the form in Figure 3.1. Next we find the attribute method, which determines whether we want the data to be submitted with a GET or a POST request. Now suppose that we completed the form by entering the value Ballard into the surname field. On submitting the form by clicking the Send button, we are taken to http://www.sometargetdomain.com/somepage.htm, where the submitted data will be processed—perhaps adding the surname to a database, for example.
33
34
Lesson 3
The variable surname (the name attribute given to the Your Surname input field) and its value (the data we entered in that field) will also have been sent to this destination page, encoded into the body of the POST request and invisible to users. Now suppose that the first line of the form code reads as follows:
On using the form, we would still be taken to the same destination, and the same variable and its value would also be transmitted. This time, however, the form would construct and send a GET request containing the data from the form. Looking at the address bar of the browser, after successfully submitting the form, we would find that it now contains: http://www.example.com/page.htm?surname=Ballard
Here we can see how the parameter and its value have been appended to the URL. If the form had contained further input fields, the values entered in those fields would also have been appended to the URL as parameter=value pairs, with each pair separated by an & character. Here’s an example in which we assume that the form has a further text input field called firstname: http://www.example.com/page.htm?surname=Ballard&firstname=Phil
Some characters, such as spaces and various punctuation marks, are not allowed to be transmitted in their original form. The HTML form encodes these characters into a form that can be transmitted correctly. An equivalent process decodes these values at the receiving page before processing them, thus making the encoding/decoding operation essentially invisible to the user. We can, however, see what this encoding looks like by making a GET request and examining the URL constructed in doing so. Suppose that instead of the surname field in our form we have a fullname field that asks for the full name of the user and encodes that information into a GET request. Then, after submitting the form, we might see the following URL in the browser: http://www.example.com/page.htm?fullname=Phil+Ballard
Sending Requests Using HTTP
Here the space in the name has been replaced by the + character; the decoding process at the receiving end removes this character and replaces the space.
Note In many cases, you may use either the POST or GET method for your form submissions and achieve essentially identical results. The difference becomes important, however, when you learn how to construct server calls in Ajax applications.
The XMLHTTPRequest object at the heart of all Ajax applications uses HTTP to make requests of the server and receive responses. The content of these HTTP requests are essentially identical to those generated when an HTML form is submitted.
Summary This lesson covered some basics of server requests and responses using the HTTP protocol, the main communications protocol of the World Wide Web. In particular, we discussed how GET and POST requests are constructed, and how they are used in HTML forms. Additionally, we saw some examples of responses to these requests that we might receive from the server.
35
LESSON 4
Client-Side Coding Using JavaScript In this lesson we introduce the concept of client-side scripting using JavaScript. Client-side scripts are embedded in web pages and executed by a JavaScript interpreter built into the browser. They add extra functionality to an otherwise static HTML page.
About JavaScript JavaScript was developed from a language called LiveScript, which was developed by Netscape for use in its early browsers. JavaScript source code is embedded within the HTML code of web pages and interpreted and executed by the browser when the page is displayed. Using JavaScript, you can add extra functionality to your web pages. Examples include • Change the way page elements are displayed • Add animation and other image effects • Open pop-up windows and dialogs • Check the validity of user-entered data Nearly all modern browsers support JavaScript, though with a few differences in some commands. Where these occur, they are described in the text.
Caution Although JavaScript is likely to be supported by your browser, it is usually possible for the browser options to be configured so as to disable its use. If you find that you cannot get any JavaScript commands to work, consult your browser’s help files to find out how to check whether JavaScript is correctly enabled.
Note Microsoft’s Internet Explorer browser actually runs a proprietary Microsoft language called Jscript, instead of JavaScript. The two are, however, virtually identical and therefore largely compatible. Where differences occur, they are described in the text.
Why Do I Need To Know About JavaScript? The j in Ajax stands for JavaScript; you use functions written in this language and embedded within your web pages to formulate Ajax server calls and to handle and process the response returned from the server.
What Is (and Isn’t) Covered in This Lesson There is no room here for an exhaustive guide to all JavaScript’s functions. Instead this lesson concentrates on those aspects of the language necessary for later developing Ajax applications. After completing this lesson, you’ll have experience with the following: • Embedding JavaScript commands and external JavaScript files into web pages • Using some of the common JavaScript commands • Using event handlers to launch JavaScript commands • Working with JavaScript variables and objects • Abstracting JavaScript commands into functions
38
Lesson 4
Tip For a much more thorough course in JavaScript, try Sams Teach Yourself JavaScript in 24 Hours by Michael Moncur.
JavaScript Basics JavaScript commands can be embedded directly into HTML pages by placing them between … tags. It is also common for JavaScript functions to be kept in a separate file on the server (usually with a file extension .js) and linked to HTML files where required, by placing a line like this into the head of the HTML file:
This allows you to call any JavaScript within the file myJS.js, just as if that source code had been typed directly into your own web page.
Tip Placing JavaScript functions into external files allows them to be made available to a number of different web pages without having to retype any code. It also makes them easier to maintain because the latest version is automatically linked into the calling HTML page each time that page is requested. It is possible to build up substantial JavaScript libraries in this way, linking them into web pages when their particular functions are required.
In at the Deep End Let’s get right to it and add a JavaScript command to the simple web page we developed in Lesson 2, “Writing Web Pages in HTML.” Open your favorite text editor and load up seville.html (Listing 2.2 from Lesson 2). We’re going to add the following code to the page, immediately after the (the closing paragraph tag) on line 24:
Client-Side Coding Using JavaScript
document.writeln(“This line was written using JavaScript!”);
Caution JavaScript, unlike HTML, is case sensitive. When entering JavaScript commands, be careful not to enter characters in the incorrect case, or errors will occur.
The whole of the source code with the extra lines added is shown in Listing 4.1. Make sure that you have added the code correctly; then save the file as testpage3.html and load it into your favorite browser.
LISTING 4.1
Adding JavaScript to an HTML Page
A Simple HTML Document A More Advanced HTML Page Welcome to my second page written in HTML.
Vegetables
Fruits
Carrot
Apple
Cabbage
Orange
continues
39
40
Lesson 4
LISTING 4.1
Continued
... and here’s some text in a paragraph.
document.writeln(“This line was written using JavaScript!”)
If all has gone well, the page should now be like that shown in Figure 4.1. You should now be able to see an extra line of text toward the bottom of the page saying “This line was written using JavaScript!”
FIGURE 4.1
HTML document including one line written by JavaScript.
Let’s look at our JavaScript code. The first item is the tag, and here we have included the definition Language=”JavaScript”
which tells the browser that the statements contained within this script element should be interpreted as JavaScript.
Client-Side Coding Using JavaScript
Also in this tag appears the attribute type=”text/javascript”
This declares that the script enclosed in the element is written in JavaScript.
Tip There are other possible languages in which such scripts could be written; each has its own type declaration such as type=”text/vbscript”
or type=”text/xml”
The script is ended on the next to the last line with the familiar tag. Now for the meat in the sandwich: document.writeln(“This line was written using JavaScript!”)
JavaScript (in common with many other programming languages) uses the concept of objects. The word document in this line of code refers to the object on which we want our JavaScript command to operate. In this case, we are dealing with the document object, which is the entire HTML document (including any embedded JavaScript code) that we are displaying in the browser. We’ll have a further look at objects later in the lesson. The term writeln describes the operation we want JavaScript to perform on the document object. We say it is a method of the document object, in this case one that writes a line of text into the document.
Note In addition to methods, objects also possess properties. Such properties tell you something about the object, as opposed to the object’s methods, which perform actions upon it.
41
42
Lesson 4
The string within the parentheses we refer to as the argument that we pass to the writeln method. In this case it tells the method what to write to the document object.
Including JavaScript in HTML Pages We can include as many … tags in our page as we need. However, we must pay some attention to where in the document they are placed. JavaScript commands are executed in the order in which they appear in the page. Note from Listing 4.1 that we entered our JavaScript code at exactly the place in the document where we want the new text to appear. JavaScript can also be added to the head section of the HTML page. This is a popular place to keep JavaScript functions, which we’ll describe shortly.
Event Handlers Often you want your JavaScript code to be executed because something specific has occurred. In an HTML form, for instance, you may decide to have JavaScript check the validity of the data entered by the user at the moment when the form is submitted. On another occasion, you may want to alert your user by opening a warning dialog whenever a particular button is clicked. To achieve these effects you use special interfaces provided by the browser and known as event handlers. Event handlers allow you to call JavaScript methods automatically when certain types of events occur. Consider the following code:
Here we capture the action of the user clicking the button, using the onClick event handler. When the user’s click is detected, the script carries out the instructions listed in the onClick attribute of the input tag: onClick=”alert(‘Thanks for clicking!’)”
Client-Side Coding Using JavaScript
This line calls the JavaScript alert method, which pops up a dialog box displaying a message and an OK button. The message to be displayed in the alert dialog is contained in the string passed to the alert method as an argument. Let’s add this code to our HTML document, as shown in Listing 4.2. Save the page as testpage4.html after you’ve made the changes and load it into the browser.
LISTING 4.2
Calling alert() from the onClick Event Handler
A Simple HTML Document A More Advanced HTML Page Welcome to my second page written in HTML.
Vegetables
Fruits
Carrot
Apple
Cabbage
Orange
... and here’s some text in a paragraph.
document.writeln(“This line was written using JavaScript!”)
43
44
Lesson 4
Our HTML page should now show our new button, as in Figure 4.2.
FIGURE 4.2
The new Click Here button in our web page.
Go ahead and click on the button. If everything goes according to plan, an alert dialog pops open as shown in Figure 4.3. You can click OK to clear the dialog.
Creating Functions Often you will need to combine various JavaScript methods and objects, perhaps using many lines of code. JavaScript allows you to compose such blocks of instructions and name them, making your code easier to write, understand, and maintain. For example, let’s use another event handler, but this time we’ll use it to call a function rather than to directly call a JavaScript method.
Client-Side Coding Using JavaScript
FIGURE 4.3 button.
The dialog that appears after you click on the new
Here’s the code for our function, which we’ll place in the head section of our HTML document: function showAlert() { alert(“A Picture of Seville”) }
Note Note that a function definition always starts with the word function followed by the function’s name. The statements within a function are contained within curly braces {}.
45
46
Lesson 4
Within the usual tags, we have now defined a function called showAlert, which carries out the commands contained within the curly braces. In this case, there is only one command, a call to the previously encountered alert method. We want this alert dialog to appear when the user’s mouse passes over the photograph in our web page. We are therefore going to add an attribute to the tag that contains the image, as follows:
This line uses the onMouseOver event handler to detect when the cursor enters the area occupied by the photograph. When this happens, our new function showAlert is called. Listing 4.3 shows the revised code.
LISTING 4.3
Using the onMouseOver Event Handler
A Simple HTML Document function showAlert() { alert(“A Picture of Seville”) } A More Advanced HTML Page Welcome to my second page written in HTML.
Vegetables
Fruits
Carrot
Client-Side Coding Using JavaScript
Apple
Cabbage
Orange
... and here’s some text in a paragraph.
document.writeln(“This line was written using JavaScript!”)
With this HTML document loaded into your browser, roll your mouse over the photograph. An alert box should appear with the message “A Picture of Seville”.
Passing Arguments to Functions Of course, we could easily call our function from a wide variety of event handlers within our page and have it pop open an alert dialog. Unfortunately, the alert would always contain the message “A Picture of Seville”, which is not very useful! Wouldn’t it be good if we could tell the function what message to display so that we could have different alert messages for different circumstances? We can achieve this by passing the message to our function as an argument: function showAlert(message) { alert(message) }
The function now “expects” to find the text for the message defined passed as an argument within the call. Rewrite the onMouseOver event handler for the image to provide this:
47
48
Lesson 4
We’ll also rewrite the button’s onClick event handler to use this function but with a different message:
Listing 4.4 shows the revised code.
LISTING 4.4 Handlers
Calling JavaScript Functions from Event
A Simple HTML Document function showAlert(message) { alert(message) } A More Advanced HTML Page Welcome to my second page written in HTML.
Vegetables
Fruits
Carrot
Apple
Cabbage
Orange
Client-Side Coding Using JavaScript
... and here’s some text in a paragraph.
document.writeln(“This line was written using JavaScript!”)
Other Event Handlers So far you have seen examples of the onClick and onMouseOver event handlers. Many others are available for use; Table 4.1 lists a selection of the most popular event handlers.
TABLE 4.1
Some Common JavaScript Event Handlers
Event Handler
Comments
onChange
Occurs when the value in an input field changes
onClick
Occurs when a user clicks the mouse on the element in question
onLoad
Occurs when the page has finished loading
onMouseOver
Occurs when the mouse pointer enters the screen area occupied by the element in question …
onMouseOut
… and when it leaves
onSubmit
Occurs at the point a form is submitted
Manipulating Data in JavaScript You can use JavaScript to achieve much more than popping up dialog boxes. JavaScript gives you the opportunity to define and use variables and arrays, work with date and time arithmetic, and control program flow with loops and conditional branches.
49
50
Lesson 4
Variables The concept of a variable might already be familiar to you if you’ve ever done any algebra, or programmed in just about any computer language. A variable is a piece of data given a name by which you can conveniently refer to it later. In JavaScript, you declare variables with the keyword var: var speed = 63;
The preceding line of code declares the variable speed and by using the assignment operator = assigns it a value of 63. We may now use this variable in other statements: var speedlimit = 55; var speed = 63; var excess_speed = speed – speedlimit;
Variables need not be numeric; the statement var lastname = ‘Smith’;
assigns a string to the variable lastname. Both numeric and string variables may be manipulated within JavaScript statements. Consider the following code: var firstname = ‘Susan’; var lastname = ‘Smith’; document.writeln(‘Hello, ‘+ firstname + ‘ ‘ + lastname);
This code would write Hello,
Susan Smith
into our document.
Objects You met the concept of an object earlier in the lesson and saw how objects have both properties that describe them and methods that perform actions on them. Objects in JavaScript have a hierarchical relationship. References begin with the highest-level object, with subsequent levels appended separated by a period: document.image1.src
Client-Side Coding Using JavaScript
This string starts with the object document, then refers to an object image1 within that object, and finally the property src (the source file for the image).
Note In fact, the object that truly has the highest level in the object hierarchy is window, which refers to the browser screen and everything within it. In general, you don’t need to include this object; JavaScript assumes it to be there.
Suppose that we have the following HTML code somewhere in our page:
We can refer, in JavaScript, to the string that the user has typed into the lastname field by referring to the property value of the object corresponding to that field: document.form1.lastname.value
Example—Form Validation Let’s use this technique to check a user’s entered form data for validity. We want to trap the event of the user attempting to submit the form and use this event to trigger our JavaScript function, which checks the data for validity. Here’s the HTML code for our form: Enter a number from 1 to 10:
We can see here that the onSubmit event handler is called when the Submit button is clicked and calls a JavaScript function called numcheck(). We need this function to check what our user has entered for
51
52
Lesson 4
validity, and either submit the form or (if the entry is invalid) issue an error. Note the word return prior to the function call. This is here because on this occasion we want the function to tell us whether the submit method should be allowed to go ahead. We want our function to return a value of false to the form if the form submission is to be stopped. Here’s the function: function numcheck() { var numentered = document.form1.usernumber.value; if((numentered>=1)&&(numentered tags in your page as you want.
Tip Web servers normally recognize by the file extension which files contain PHP code and process them accordingly. The most used file extension for PHP files is .php, but you may also see .php3, .php4, .phtml, and various others. To make your code portable to as many web server environments as possible, it’s best to stick with .php.
Server-Side Programming in PHP
Outputting HTML from PHP Several PHP commands can help you write text and HTML code directly into your page. Perhaps the simplest is the echo command: echo “I wrote this line using PHP”;
The preceding statement simply places “I wrote this line using PHP” into the HTML document at precisely the place where the PHP statement occurs. Listing 5.1 shows the source code of a PHP file to print Hello the browser window.
LISTING 5.1
World
in
Printing Hello World in PHP
A Simple PHP Script
Note that in this script, the output string also contains some HTML tags, and . As the PHP statements are executed by the web server before serving the page to us, these tags are written into the document’s HTML along with the “Hello World” text and evaluated by our browser along with all other HTML markup in the document. Figure 5.1 shows the browser displaying our “Hello World” page. If we ask the browser to show us the source of this page, it displays the following code, in which we can see that the PHP elements have been completely evaluated by the web server, which has inserted the relevant HTML into the page: A Simple PHP Script Hello World!
55
56
Lesson 5
FIGURE 5.1
”Hello World” in PHP.
Variables in PHP Variables in PHP, much like in any programming language, are named pockets in which pieces of data are stored. All variable names in PHP must begin with a “$” character, followed by a string made up of letters, numbers, and underscores.
Caution Variable names are case sensitive in PHP. For example, $varname and $VarName represent two distinct variables. Take care to enter the names of variables in the correct case.
We can assign values to variables in PHP without declaring the variables beforehand: $score = 71; $player = ‘Harry Scott’;
Server-Side Programming in PHP
Variables can take a number of data types, including strings, integers, floats, and Boolean (true or false). When a variable is assigned a value, such as in the preceding examples, PHP assigns a data type automatically.
Numbers All the basic mathematical operators are available in PHP, as shown in the following examples: $answer $answer $answer $answer
= = = =
13 13 13 13
+ * / –
4; 4; 4; 4;
You can also calculate the modulus, for which we use the % character: $answer = 13 % 4;
Strings In PHP you enclose strings within single or double quotes: $mystring = “The quick brown fox”;
Strings may be concatenated using the period character: $newstring = “ jumped over the lazy dog”; $concat = $mystring.$newstring;
Tip PHP offers the date() command, which allows you to get the server time and date and format it to your liking; for example, the line echo date(‘D F Y H:I’);
outputs the current date in a form similar to Fri 16 December 2005 11:36.
Arrays PHP also supports arrays. An array is a variable that can contain a set of values rather than just one. Here’s a PHP array containing some of the days of the week:
The items in an array are referenced by a key, which is an integer starting at zero and incrementing for each item in the array. The following line outputs Thursday to an HTML page: echo $daynames[3];
Note that, because the index value begins at zero, the preceding statement actually echoes the fourth element of the array. This type of array is known as a numeric array, but you may also use associative arrays. In this case, the key value of each element is not numeric but instead is a string of your choosing. The syntax to declare such an array and assign values to it is slightly different: $lunch = array(“Susan” => “Chicken”, “Matthew” => “Beef”, ➥ “Louise” => “Salmon”);
You can now select the elements of such an array using the key value: echo $lunch[“Louise”];
This command would output the word Salmon to our page.
Controlling Program Flow PHP contains various structures for controlling the flow of your programs. One of the most useful is the simple if statement, which allows you to alter the flow of program execution depending on the outcome of a condition. Let’s have a look at a code snippet using the if statement: if($temp > 80) { echo $temp.” degrees is too hot. ➥ the thermostat.”; }
Turn down
This if statement simply evaluates the condition contained in the brackets. If the condition is satisfied, the statements within the curly braces are executed; otherwise, these statements are ignored.
Server-Side Programming in PHP
We can also add an else clause to our if statement: if($temp > 80) { echo $temp.” degrees is too hot. Turn down ➥ the thermostat.”; } else { echo $temp.” degrees is cool enough.”; }
PHP also has loop constructs, which allow you to repeat the same code instructions a number of times until the conditions are satisfied for the loop to be terminated. This is the code for a while loop: $x = 1; while($x