0% found this document useful (0 votes)
119 views

Paper - II Web Technology

This document provides an overview of the contents of a course on Web Technology. It outlines the 5 units that will be covered: 1) Introduction to HTML and XHTML, 2) Cascading Style Sheets and JavaScript, 3) Dynamic documents using JavaScript, 4) XML and Web Services, and 5) PHP and Ajax. Each unit covers important topics such as document structure, styling, scripting, services, and server-side programming. Key concepts, chapters from the textbook, and additional references are listed for each unit.

Uploaded by

Ahfrin J
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
119 views

Paper - II Web Technology

This document provides an overview of the contents of a course on Web Technology. It outlines the 5 units that will be covered: 1) Introduction to HTML and XHTML, 2) Cascading Style Sheets and JavaScript, 3) Dynamic documents using JavaScript, 4) XML and Web Services, and 5) PHP and Ajax. Each unit covers important topics such as document structure, styling, scripting, services, and server-side programming. Key concepts, chapters from the textbook, and additional references are listed for each unit.

Uploaded by

Ahfrin J
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 248

PERIYAR INSTITUTE OF DISTANCE EDUCATION

(PRIDE)

PERIYAR UNIVERSITY
SALEM - 636 011.

M.Sc. COMPUTER SCIENCE


FIRST YEAR
PAPER – II : WEB TECHNOLOGY

1
Prepared by :
Dr. I. LAURENCE AROQUIARAJ
Assistant Professor
Department of Computer Science
Periyar University
Periyar Palkalai Nagar
Salem – 636 011.

2
M.Sc. COMPUTER SCIENCE
FIRST YEAR
PAPER – II : WEB TECHNOLOGY

UNIT – I: Introduction HTML & XHTML


A Brief Introduction to the Internet – The World Wide Web – Web
Browsers – Web Servers, Uniform Resource Locator – Multipurpose Internet
Mail Extension – The Hypertext Transfer Protocol – Origin and Evaluation of
HTML & XHTML, Standard XHTML document structure – Basic text markup
– Images – Hypertext link – Lists – Tables – Forms – Frames – Syntactic
differences between HTML & XHTML.

UNIT – II: Cascading Style Sheet (CSS) & Java Script


Cascading Style Sheet (CSS) – Overview of Java Script – Object
Orientation & Java Script – Primitives, Operation and Expressions – Screen
Output and Keyboard Input – Control Statements – Object Creation
Modifications, Arrays – Function Construction – Pattern matching using
Regular expression.

UNIT – III: Dynamic Documents using Java Script


Java Script Execution Environment – Document Object Model(DOM) –
Element Access in Java Script – Events and Events Handling – Handling
Events from Body Elements, Button Elements, Textbox and Password
Elements – DOM Tree traversal and Modification – Positioning Elements –
Moving Elements – Elements Visibility – Changing colors and fonts –
Dynamic Content – Stacking Elements – Locating the Mouse Cursor, Reacting
to a Mouse Click – Dragging and Dropping Elements.

UNIT – IV: XML & Web services


Introduction – XML Document Structure – Document Type Definition
– Namespace – XML Schemas – Displaying Raw XML Document –
Displaying XML Document with CSS – XSLT Style Sheet – XML Processors–
Web services

3
UNIT – V: PHP & Ajax
Overview of PHP – General Syntactic characteristics – Primitives,
Operation and Exception – Output – Control Statement – Arrays – Functions –
Pattern Matching – Form Handling – Files – Cookies, Session Tracking –
MySQL database system –Database access with PHP & MySQL. Overview of
Ajax – The Basics of Ajax- Rails with Ajax.

Text Book
1. Robert W. Sebesta, Programming with World Wide Web, 4th Edition,
Pearson Education, 2008, Chapter 1-7, 11,13,4,13.6,16

Reference Books
1. Harvey & Paul Deitel& Associates, Harvey Deitel and Abbey Deitel,
“Internet and World Wide Web – How To Program”, Fifth Edition,
Pearson Education, 2011.
2. Achyut S Godbole and AtulKahate, “Web Technologies”, Second
Edition, Tata McGraw Hill, 2012.
3. Thomas A Powell, Fritz Schneider, “JavaScript: The Complete
Reference”, Third Edition, Tata McGraw Hill, 2013.
4. David Flanagan, “JavaScript: The Definitive Guide, Sixth Edition”,
O’Reilly Media, 2011
5. Steven Holzner, “The Complete Reference – PHP”, Tata McGraw Hill,
2008
6. Mike Mcgrath, “PHP & MySQL in easy Steps”, Tata McGraw Hill,
2012.

4
M.Sc. COMPUTER SCIENCE
FIRST YEAR
PAPER – II : WEB TECHNOLOGY

Unit Title
1.1 A Brief Introduction to the Internet
1.2 The World Wide Web
1.3 Web Browsers
1.4 Web Servers,
1.5 Uniform Resource Locator
1.6 Multipurpose Internet Mail Extension
1.7 The Hypertext Transfer Protocol
1.8 Origin and Evaluation of HTML & XHTML, Standard
I XHTML document structure
1.9 Basic text markup Images
1.10 Hypertext link
1.11 Lists
1.12 Tables
1.13 Forms
1.14 Frames
1.15 Syntactic differences between HTML & XHTML.
2.1 Cascading Style Sheet (CSS)
2.2 Overview of Java Script
2.3 Object Orientation & Java Script
2.4 Primitives, Operation and Expressions
II 2.5 Screen Output and Keyboard Input
2.6 Control Statements
2.7 Object Creation Modifications, Arrays
2.8 Function Construction
2.9 Pattern matching using Regular expression.

5
3.1 Java Script Execution Environment
3.2 Document Object Model(DOM)
3.3 Element Access in Java Script
III 3.4 Events and Events Handling
3.5 Handling Events from Body Elements, Button
Elements, Textbox and Password Elements
3.6 DOM Tree traversal and Modification
3.7 Positioning Elements
3.8 Moving Elements
3.9 Elements Visibility
3.10 Changing colors and fonts
3.11 Dynamic Content
3.12 Stacking Elements
3.13 Locating the Mouse Cursor, Reacting to a Mouse
Click
3.14 Dragging and Dropping Elements.
4.1 Introduction
4.2 XML Document Structure
4.3 Document Type Definition
4.4 Namespace
IV 4.5 XML Schemas
4.6 Displaying Raw XML Document
4.7 Displaying XML Document with CSS
4.8 XSLT Style Sheet
4.9 XML Processors
4.10 Web services

6
5.1 Overview of PHP
5.2 General Syntactic characteristics
5.3 Primitives, Operation and Exception
5.4 Output
V 5.5 Control Statement
5.6 Arrays – Functions
5.7 Pattern Matching
5.8 Form Handling – Files
5.9 Cookies, Session Tracking
5.10 MySQL database system
5.11 Database access with PHP & MySQL
5.12 Overview of Ajax
5.13 The Basics of Ajax- Rails with Ajax.

7
UNIT – I

INTRODUCTION HTML & XHTML


In This Chapter
 A Brief Introduction to the Internet
 The World Wide Web
 Web Browsers 1.4
 Web Servers
 Uniform Resource Locators
 Multipurpose Internet Mail Extensions
 The Hypertext Transfer Protocol
 Origin and evaluation of html & Xhtml
 XHTML document structure
 basic text markup
 Images
 Hypertext link & List
 Tables
 Forms
 Frames
 Syntactic differences between HTML & XHTML
1.1 A Brief Introduction to the Internet
The first recorded description of the social interactions that could be
enabled through networking was a series of memos written by J.C.R. Licklider
of MIT in August 1962 discussing his "Galactic Network" concept. He
envisioned a globally interconnected set of computers through which everyone
could quickly access data and programs from any site. In spirit, the concept was
very much like the Internet of today. Licklider was the first head of the
computer research program at DARPA, starting in October 1962. While at
DARPA he convinced his successors at DARPA, Ivan Sutherland, Bob Taylor,
and MIT researcher Lawrence G. Roberts, of the importance of this networking
concept.
Leonard Klein rock at MIT published the first paper on packet
switching theory in July 1961 and the first book on the subject in 1964. Klein
rock convinced Roberts of the theoretical feasibility of communications using
packets rather than circuits, which was a major step along the path towards

8
computer networking. The other key step was to make the computers talk
together. To explore this, in 1965 working with Thomas Merrill, Roberts
connected the TX-2 computer in Mass. to the Q-32 in California with a low
speed dial-up telephone line creating the first (however small) wide-area
computer network ever built. The result of this experiment was the realization
that the time-shared computers could work well together, running programs and
retrieving data as necessary on the remote machine, but that the circuit switched
telephone system was totally inadequate for the job. Kleinrock's conviction of
the need for packet switching was confirmed.
In late 1966 Roberts went to DARPA to develop the computer network
concept and quickly put together his plan for the "ARPANET", publishing it in
1967. At the conference where he presented the paper, there was also a paper
on a packet network concept from the UK by Donald Davies and Roger
Scantlebury of NPL. Scantlebury told Roberts about the NPL work as well as
that of Paul Baran and others at RAND. The RAND group had written a paper
on packet switching networks for secure voice in the military in 1964. It
happened that the work at MIT (1961-1967), at RAND (1962-1965), and at
NPL (1964-1967) had all proceeded in parallel without any of the researchers
knowing about the other work. The word "packet" was adopted from the work
at NPL and the proposed line speed to be used in the ARPANET design was
upgraded from 2.4 kbps to 50 kbps.
In August 1968, after Roberts and the DARPA funded community had
refined the overall structure and specifications for the ARPANET, an RFQ was
released by DARPA for the development of one of the key components, the
packet switches called Interface Message Processors (IMP's). The RFQ was
won in December 1968 by a group headed by Frank Heart at Bolt Breakneck
and Newman (BBN). As the BBN team worked on the IMP's with Bob Kahn
playing a major role in the overall ARPANET architectural design, the network
topology and economics were designed and optimized by Roberts working with
Howard Frank and his team at Network Analysis Corporation, and the network
measurement system was prepared by Kleinrock's team at UCLA.
Due to Klein rock’s early development of packet switching theory and
his focus on analysis, design and measurement, his Network Measurement
Center at UCLA was selected to be the first node on the ARPANET. All this
came together in September 1969 when BBN installed the first IMP at UCLA
and the first host computer was connected. Doug Engelbart's project on
"Augmentation of Human Intellect" (which included NLS, an early hypertext
system) at Stanford Research Institute (SRI) provided a second node. SRI
supported the Network Information Center, led by Elizabeth (Jake) Feinler and

9
including functions such as maintaining tables of host name to address mapping
as well as a directory of the RFC's.
One month later, when SRI was connected to the ARPANET, the first
host-to-host message was sent from Kleinrock 's laboratory to SRI. Two more
nodes were added at UC Santa Barbara and University of Utah. These last two
nodes incorporated application visualization projects, with Glen Culler and
Burton Fried at UCSB investigating methods for display of mathematical
functions using storage displays to deal with the problem of refresh over the
net, and Robert Taylor and Ivan Sutherland at Utah investigating methods of 3-
D representations over the net. Thus, by the end of 1969, four host computers
were connected together into the initial ARPANET, and the budding Internet
was off the ground. Even at this early stage, it should be noted that the
networking research incorporated both work on the underlying network and
work on how to utilize the network. This tradition continues to this day.
Computers were added quickly to the ARPANET during the following
years, and work proceeded on completing a functionally complete Host-to-Host
protocol and other network software. In December 1970 the Network Working
Group (NWG) working under S. Crocker finished the initial ARPANET Host-
to-Host protocol, called the Network Control Protocol (NCP). As the
ARPANET sites completed implementing NCP during the period 1971-1972,
the network users finally could begin to develop applications.
In October 1972, Kahn organized a large, very successful demonstration
of the ARPANET at the International Computer Communication Conference
(ICCC). This was the first public demonstration of this new network
technology to the public. It was also in 1972 that the initial "hot" application,
electronic mail, was introduced. In March Ray Tomlinson at BBN wrote the
basic email message send and read software, motivated by the need of the
ARPANET developers for an easy coordination mechanism. In July, Roberts
expanded its utility by writing the first email utility program to list, selectively
read, file, forward, and respond to messages. From there email took off as the
largest network application for over a decade. This was a harbinger of the kind
of activity we see on the World Wide Web today, namely, the enormous growth
of all kinds of "people-to-people" traffic.
1.2 The World Wide Web
This section provides a brief introduction to the evolution of the World
Wide Web.
What is the World Wide Web?
 The World Wide Web is a user interface to the Internet. The Internet is
a set of computers connected to each other with a network. Each of

10
these computers either knows how to speak, (or knows another
computer that knows how to speak), a language called TCP/IP.
 Here is a picture of the Internet in North America. The heavy white
lines are what are known as the "Backbone" of the Internet. Each yellow
or pink line is a connection to a "Provider" such as OARnet. OARnet is
our Internet provider (along with a great many other schools and
businesses in Ohio). Soon, MCI will also be providing Internet services
to us. Each little green dot is connected to hundreds (even thousands) of
other networks such as the network we have at Ohio University.
 The World Wide Web is an easy to use, transparent user interface to
these computers. You don't need to know where the computers are or
how many exist, in order to use the World Wide Web. That is its allure.
The World Wide Web is to the Internet as Microsoft Windows (or a
Macintosh) is to DOS.
A brief history of the WWW
 The World Wide Web got started because it was just plain too difficult
to get at all of the information that is on the Internet. The only people
who could do it were the computer geeks. The learning curve for
accessing information on the Internet was indeed very steep. Basically,
if you weren't a UNIX or VMS guru, you were left out of the Internet.
 The first effort to make the Internet accessible to less geeky types was
called gopher. Gopher was developed for use on terminal screens. It
offered a very nice interface to the net. A user could move up and down
along the screen and pick choices by highlighting a topic and pressing
the enter key. When a useful document was presented, another press of
the enter key downloaded it to your local terminal.
 Unfortunately Gopher didn't really come into its own. In this age of
mice and windows, users demand mo re, MUCH more than a simple
terminal based interface. Think of Gopher as DOS SHELL or
PCTOOLS to the Internet. Better than DOS, but nobody uses them
anymore.
 Enter Hypermedia. If you have ever used HyperCard on the Mac or a
Windows help file you know all about hypermedia. It is a method of
presenting a user with text (or other things) that can be clicked with a
mouse. There are two different types of text presented, normal text
which is to be read, and highlighted text which can be clicked (or
invoked somehow).

11
 So, now that you are bored to tears, the World Wide Web is a
hypermedia interface similar to HyperCard or Windows Help, to the
Internet. A user is presented with text, pictures, movies, sound and just
about anything someone can dream up, that is clickable. So the Internet
has finally become something people can use. Much to the despair of
the geeks.
The World Wide Web uses three protocols:
 HTML (Hypertext markup language) - The language that we write
our web pages in.
 HTTP (Hypertext Transfer Protocol) - Although other protocols can
be used such as FTP, this is the most common protocol. It was
developed specifically for the World Wide Web and favored for its
simplicity and speed. This protocol requests the 'HTML' document from
the server and serves it to the browser.
 URLS (Uniform resource locator) - The last part of the puzzle required
to allow the web to work is a URL. This is the address which indicates
where any given document lives on the web. It can be defined
as<protocol>://<node>/<location>
1.3 Web Browsers Introduction
A web browser is a software application which enables a user to display
and interact with text, images, videos, music, and other information that could
be on a website. Text and images on a web page can contain hyperlinks to other
web pages at the same or different website. Web browsers allow a user to
quickly and easily access information provided on many web pages at many
websites by traversing these links. Web browsers format HTML information
for display so the appearances of a web page many differs between browsers.
Protocols and Standards
Web browsers communicated with web servers primarily using HTTP
(hypertext transfer protocol) to fetch web pages. HTTP allows web browsers to
submit information to web servers as well as fetch web pages from them. Pages
are identified by means of a URL (uniform resource locater), which is treated
as an address, beginning with “http://” for HTTP access.
The file format for a web page is usually HTML (hyper-text markup
language) and is identified in the HTTP protocol. Most web browsers also
support a variety of additional formats, such as JPEG, PNG, and GIF image
formats, and can be extended to support more through the use of plugins. The
combination of HTTP content type and URL protocol specification allows web

12
page designers to embed images, animations, video, sound, and streaming
media into a web page, or to make them accessible through the web page.
Popular Browsers
Browser Statistics:
The most popular browsers as follow in terms of market share:
 Google Chrome
 Mozilla Firefox
 Internet Explorer
 Safari
 Opera
These were the data known as of December 2014, with Google Chrome
as the main browser today, and it shows how statistics have changed
throughout the years. Although these statistics may not be accurate, they give
you an idea of what are the preferred browsers, but here is a more detailed list
of the browsers and their characteristics.
Internet Explorer
For years the most popular browser, Microsoft’s Internet
Explorer’s rate of use has increasingly decreased through
the years. However, its newest version, Internet Explorer
11, features some interesting things, and make it worthy of
consideration again: It is faster, has a cleaner interface,
smaller notifications, security is upgraded, and features tab isolation (so that not
all your tabs crash when one does), a feature first seen in Google’s Chrome. It
also features one box for both addresses and web search, again something
Chrome started doing, and a download manager. It supports HTML5, CSS3 and
SVG. It was formally released on 17 October 2013 for Windows 8.1 and on 7
November 2013 for Windows 7. A downside is that Internet Explorer 11 for
Windows RT does not support Java. Microsoft is working on the Internet
Explorer 12 version, in order to be applied to Windows 9. In this version,
several improvements have been introduced, like the treatment of images (since
the srcset has been developed for a responsive size, depending on the device
used) or the introduction of the <main> element from HTML5 for a better user
experience

13
Firefox
In 2003 Mozilla’s browser, Firefox, started
competing with Internet Explorer, becoming more
popular than it quickly. A cross-platform browser,
it works on Windows, Mac OS X and Linux, and it
is one of the most standard-compliant browsers.
Among its most appealing characteristics are a
better rendering of the web pages compared to
Internet Explorer, add-ons and extensions to
personalize your searches, session restoration, a download manager and pop-up
blocking. It also features the all-in-one address and search bar, although it also
has a separate search bar that you can personalize to browse in Google, Yahoo,
Bing, or even other websites, like dictionaries, Wikipedia, etc. It supports
HTML5, CSS3 and it enables developers to create full-screen video content and
apps.
Chrome
Launched by Google in 2008, Chrome was meant to
rethink browsing completely. It is the most used browser
today, and its popularity continues to grow, as it has
lived up to the users’ expectations. Chrome was the first
browser to introduce tab isolation and one box for both
addresses and searches, and it started as a faster and cleaner browser. Aside
from all of this, it also includes some useful features, like a quick calculation
system included in the address bar, or drag and drop downloads and searches,
as well as developer resources. It also enables multiple profiles in one window,
and allows you to access your printer from any enabled web app through
Google Cloud Print.
Safari

Apple’s Safari was initially developed for Mac OS, but it


was later introduced to Windows (XP, Vista or 7). It is
the default browser for Mac, but it doesn’t rank very high
in number of users. Standards-compliant, browsing with
it is fast and secure, and supports HTML5, CSS3 and
SVG. An interesting feature of this browser is that it removes advertisements
and pop-ups and leaves just the text, to allow you to read any given article
without being bothered by these. Like all browsers now, it enables DNS
prefetching to allow users to make searches using the address bar.

14
Opera
The least popular of the browsers listed, Opera initially
required a user fee, but is now free. It supports all major
web standards, including HTML5, CSS3 and SVG, and it
works on Mac OS X, Windows and Linux. Although it
may not offer as many features as other browsers, it has
the sleekest interface and is fast, secure and very easy to
use. The Operating Systems compatible with this browser are Microsoft
Windows, Mac OS X and GNU/Linux (Ubuntu 64-bit). The last version was
launched on 3rd December 2014, called Opera 26.
And then other browsers list:
o Maxthon
o Netscape Browser
o YouTube Browser
o UC Browser
o Avant
1.4 Web Servers
The web server software offers access to documents stored on the server.
Clients can browse the documents in a web browser. The documents can be for
example static Hypertext Markup Language (HTML) files, image files or
various script files, such as Common Gateway Interface (CGI), Java script or
Perl files.
The communication between clients and server is based on the
Hypertext Transfer Protocol (HTTP). When a document on the web server is
requested, an HTTP request is constructed and sent to the server. The HTTP
request is encapsulated in a TCP segment. Figure 1.1 illustrates the TCP
contains the port address (the destination application on the server, i.e. the web
server software) and is in its turn encapsulated into IP packets containing the IP
address of the server. On local area networks, the IP packets are put into
Medium Access Control (MAC) frames that address the next computer on the
route towards the server.
Figure 1.2 shows the decomposition of an HTTP request into TCP
segments, IP packets and MAC frames. An HTTP transaction consists of three
steps: TCP connection setup, HTTP layer processing and network processing.
The TCP connection setup is performed as a so called three-way handshake,
where the client and the server exchange TCP SYN, TCP SYN/ACK and TCP
ACK messages. Once the connection has been established, a document request
can be issued with an HTTP GET message to the server. The server then replies

15
with a HTTP GET REPLY message. Finally, the TCP connection is closed by
sending TCP FIN and TCP ACK messages in both directions.
There are many web servers on the market today. Four main types can be
identified; process-driven, threaded, event-driven and in-kernel web servers.
Threaded and process-driven web servers are the most common, with Apache
being the most popular currently. Another popular process-driven web server is
Microsoft’s IIS, covering about 21 percent of the market.
Examples of event-driven web servers are Zeus and Flash. A description
of event-driven web servers and overload control strategies for such servers is
found in. In-kernel web servers are servers that are executed in the operating
system kernel.

Figure 1.1: The Structure of the HTTP request.


Apache
Introduced in 1995 and based on the popular NCSA http 1.3, Apache
is now the most used web server in the world (Net craft )It is used in more than
67 percent of all web server systems (more than 52 million in total, July 2004).
One of the reasons to its popularity is that it is free to use. Also, since the
source code is free, it is possible to modify the web server.
Being threaded (threaded or process-driven depending on the
operating system, on Unix, Apache uses processes, while threads are used in
Win32 environments) means that Apache maintains a pool of software threads
ready to serve incoming requests. Should the number of active threads run out,
more can be created?
When a request enters the web server, it is assigned one of the free
threads that serve it throughout the requests lifetime. Apache puts a limit on the
number of threads that are allowed to run simultaneously. If that number has
been reached, requests are rejected.

16
Figure 1.2: The TCP Session.
Modules in Apache
What makes Apache so attractive is also its architecture. The software is
arranged in a kernel part and additional packages called modules. The kernel is
responsible for opening up sockets for incoming TCP connections, handling
static files and sending back the result. Whenever something else than a static
file is to be handled, one of the designated modules takes over.
For example, if a page with a CGI script is requested, the mod cgi
module launches the CGI engine, executes the script and then returns the
finished page to the kernel. Modules are convenient when new functionality
should be added to a web server, because nothing has to be changed in the
kernel. A new module can be programmed to respond to a certain type of
request.
Modules communicate with the kernel with hooks that are well defined
points in the execution of a request. In Apache, every request goes through a
life-cycle that consists of a number of phases,. The phases are for example
Child Initialization, Post Read Request, Handlers, and Logger. When a module
wishes to receive a request it has to register a hook in the kernel.
The shaded phases represent the phases that occur during the startup of
the web server. Child initialization and exit phases are only called once in
Win32 environments. In a process-driven environment (UNIX), they are called
for all requests more of the phases. For example, mod CGI is registered to be
notified in the Handlers phase, which means that once the request has reached

17
so far in the kernel, it is delivered to the mod CGI module. Mod CGI then
performs its duties and returns the request back to the kernel.
The kernel checks whether other modules want to get a hold of the
request in the Handlers phase before continuing to the next phase (Logger).
Types of web server:
 This server is always connected to the internet. Every Web server that is
connected to the Internet is given a unique address made up of a series
of four numbers between 0 and 255 separated by periods. For example,
68.178.157.132 or 68.122.35.127.
 When you register a Web address, also known as a domain name, such
as tutorialspoint.com you have to specify the IP address of the Web
server that will host the site. You can load up with Dedicated Servers
that can support your web-based operations.
 There are four leading web servers: Apache, IIS, lighttpd and Jagsaw.
Now we will see these servers in bit more detail.
 Apart from these Web Servers, there are other Web Servers also
available in the market but they are very expansive. Major ones are
Netscape's iPlanet, Bea's Web Logic and IBM's Web sphere.
Apache HTTP Server
o This is the most popular web server in the world developed
by the Apache Software Foundation. Apache web server is
open source software and can be installed on almost all
operating systems including Linux, UNIX, Windows,
FreeBSD, Mac OS X and more. About 60% of the web
server machines run the Apache Web Server.
o You can have Apache with tomcat module to have JSP and
J2EE related support.
You can have detailed information about this server at Apache HTTP Server
Internet Information Services
o The Internet Information Server (IIS) is a high performance Web
Server from Microsoft. This web server runs on Windows
NT/2000 and 2003 platforms (and may be on upcoming new
Windows version also). IIS comes bundled with Windows
NT/2000 and 2003; Because IIS is tightly integrated with the
operating system so it is relatively easy to administer it.
o You can have detailed information about this server at Microsoft
IIS

18
lighttpd
o The lighttpd, pronounced lightly is also a free web server that
is distributed with the FreeBSD operating system. This open
source web server is fast, secure and consumes much less
CPU power. Lighttpd can also run on Windows, Mac OS X,
Linux and Solaris operating systems.
o You can have detailed information about this server at lighttpd

Sun Java System Web Server


o This web server from Sun Microsystems is suited for medium
and large web sites. Though the server is free it is not open
source. It however, runs on Windows, Linux and UNIX
platforms. The Sun Java System web server supports various
languages, scripts and technologies required for Web 2.0 such
as JSP, Java Servlets, PHP, Perl, Python, Ruby on Rails, ASP
and Coldfusion etc.
o You can have detailed information about this server at Sun
Java System Web Server

Jigsaw Server
o Jigsaw (W3C's Server) comes from the World Wide Web
Consortium. It is open source and free and can run on various
platforms like Linux, UNIX, Windows, and Mac OS X Free
BSD etc. Jigsaw has been written in Java and can run CGI
scripts and PHP programs.
o You can have detailed information about this server at Jigsaw
Server
1.5 Uniform Resource Locators
What are the Uniform Resource Locators?
 Introduction
 How to enter a Uniform Resource Locators
 Breaking Down a common Uniform Resource Locators
 Important
 Interesting tidbit
 Vocabulary and glossary

19
Introduction
The World Wide Web uses Uniform Resource Locators (or URLs) to
specify files on other servers. The Web technology integrates the many wide
and varied data management tools available on the Internet. Data management
tools are used to store information in a hierarchical structure and each has its
own viewing or access tool. For example, Gopher, WAIS and news systems.
How to Enter a Universal Resource Locator?
 Point and click your mouse into the address bar.
 Clicking in the address bar may select the existing text, making it turn a solid
color (such as blue). From this point you may start typing to replace the
existing text, or if it doesn't turn a solid color
 You may have to erase the existing website address. Depending on where
your insertion point is, you may use the Delete or Backspace button. The
Delete button on the keyboard erases what is in front (or to the right) of the
cursor, and the Backspace button erases what is in back (or to the left) of it.
 Type the address you want to visit.
 Press the Enter button on your keyboard.
Breaking Down a common Uniform Resource Locators

http://
This Web server uses Hypertext Transfer Protocol (HTTP). This is the
most common protocol on the Internet. Hypertext Transfer Protocol is a
procedure used to request and transmit files. The coded format language used
for creating documents on the WWW and controlling how web pages appear.
 www
This site is on the World Wide Web.
 yahoo
The Web server is at yahoo.
 com
This is a common extension for commercial sites. Others include:
o .edu (educational institution)
o .gov (government)

20
o .mil (military)
o .net (network)
o .org (organization)
Important
 Do not assume you know the URL for a website. There are companies
and/or persons who have purchased the use of common misspelled web
addresses. This is known as “typo squatting” or a “mousetrap”. Using the
incorrect URL for a website could lead you to a page where you never
intended to go. It may take you to a page that will try to solicit you or
shock you. Be careful and know your addresses.
Interesting Tidbit
 You do not have to type http:// into the address bar every time you enter an
address. It will be assumed that you want the page to be found using this
protocol.
 Another interesting fact is that you may use your address bar to search for
topics. So instead of entering a URL, you may enter just a keyword that
you would like to search.
 After you enter the keyword, press enter on the keyboard or use the
address bar button. The search results will use a common search engine,
perhaps your default setting, and give you a list of results.
Vocabulary and Glossary
 Address Bar
A horizontal area at the top of the browser window where you enter the
web address of the website that you would like to visit.
 Browser
A browser is a software program used to access and navigate the Internet.
It is used to enable users to view web pages.
 Hypertext Transfer Protocol (HTTP)
HTTP is a procedure used to request and transmit files. It is the coded
format language used for creating documents on the WWW and
controlling how web pages appear.
 Universal Resource Locator (URL)
This is a unique address for website or webpage. The URL is entered in
the address bar of a window.

21
1.6 Multipurpose Internet Mail Extensions (MIME)
MIME (Multi-Purpose Internet Mail Extensions) is an extension of the
original Internet e-mail protocol that lets people use the protocol to exchange
different kinds of data files on the Internet: audio, video, images, application
programs, and other kinds, as well as the ASCII text handled in the original
protocol
The Simple Mail Transport Protocol (SMTP). In 1991, Nathan
Bornstein of Bell core proposed to the IETF that SMTP be extended so that
Internet (but mainly Web) clients and servers could recognize and handle other
kinds of data than ASCII text. As a result, new file types were added to "mail"
as a supported Internet Protocol file type
Servers insert the MIME header at the beginning of any Web
transmission. Clients use this header to select an appropriate "player"
application for the type of data the header indicates. Some of these players are
built into the Web client or browser (for example, all browsers come with GIF
and JPEG image players as well as the ability to handle HTML files).
Other players may need to be downloaded. New MIME data types are
registered with the Internet Assigned Numbers Authority (IANA).
MIME is specified in detail in Internet Request for Comments 1521
and 1522, which amend the original mail protocol specification, RFC 821 (the
Simple Mail Transport Protocol) and the ASCII messaging header, RFC 822.
Type Specifications
MIME was developed to specify the format of different kinds of
documents to be sent via Internet mail. These documents could contain various
kinds of text, video data, or sound data. Because the Web has needs similar to
those of Internet mail, MIME was adopted as the way to specify document
types transmitted over the Web.
A Web server attaches a MIME format specification to the beginning
of the document that it is about to provide to a browser. When the browser
receives the document from a Web server, it uses the included MIME format
specification to determine what to do with the document. If the content is text,
For example, the MIME code tells the browser that it is text and also
indicates the particular kind of text it is. If the content is sound, the MIME code
tells the browser that it is sound and then gives the particular representation of
sound so that the browser can choose a program to which it has access to
produce the transmitted sound.

22
MIME specifications have the following form:
Type/subtype
 The most common MIME types are text, image, and video. The most
common text subtypes are plain and html. Some common image
subtypes are gif and jpeg. Some common video subtypes are mpeg and
QuickTime. A list of MIME specifications is stored in the
configuration files of every Web server. In the remainder of this book,
when we say document type, we mean both the document’s type and its
subtype.
 Servers determine the type of a document by using the filename’s
extension as the key into a table of types. For example, the extension
.html tells the server that it should attach text/html to the document
before sending it to the requesting browser.
 Browsers also maintain a conversion table for looking up the type of a
doc-ument by its file name extension. However, this table is used only
when the server does not specify a MIME type, which may be the case
with some older servers. In all other cases, the browser gets the
document type from the MIME header provided by the server.
1.7 The Hypertext Transfer Protocol
 All Web communications transactions use the same protocol: the Hyper-
text Transfer Protocol (HTTP).
 The current version of HTTP is 1.1, for-mally defined as RFC 2616,
which was approved in June 1999.
 RFC 2616 is available at the Web site for the World Wide Web
Consortium.
 HTTP consists of two phases: the request and the response. Each HTTP
communication (request or response) between a browser and a Web
server con-sists of two parts: a header and a body. The header contains
information about the communication the body contains the data of the
communication if there is any.
The Request Phase
The general form of an HTTP request is as follows:
1. HTTP method Domain part of the URL HTTP version
2. Header fields
3. Blank line
4. Message body

23
Only a few request methods are defined by HTTP, and even a smaller
number of these are typically used. Table 1.1 lists the most commonly used
methods.
Table 1.1 HTTP request methods
Method Description
GET Returns the contents of the specified document
HEAD Returns the header information for the specified document
POST Executes the specified document, using the enclosed data
PUT Replaces the specified document with the enclosed data
DELETE Deletes the specified document
Among the methods given in Table 1.1, GET and POST are the most
frequently used. POST was originally designed for tasks such as posting a news
article to a newsgroup. It’s most common use now is to send form data from a
browser to a server, along with a request to execute a program on the server that
will process the data.
Following the first line of an HTTP communication is any number of
header fields, most of which are optional. The format of a header field is the
field name followed by a colon and the value of the field.
There are four categories of header fields:
1. General: For general information, such as the date
2. Request: Included in request headers
3. Response: For response headers
4. Entity: Used in both request and response headers
One common request field is the Accept field, which specifies a
preference of the browser for the MIME type of the requested document. More
than one Accept field can be specified if the browser is willing to accept
documents in more than one format.
For example; we might have any of the following:
Accept:
text/plain
Accept:
text/html
Accept:
image/gif

24
A wildcard character, the asterisk (*), can be used to specify that part
of a MIME type can be anything. For example, if any kind of text is acceptable,
the Accept field could be as follows:
Accept: text/*
The Host:
 Host name request field gives the name of the host. The Host field is
required for HTTP 1.1. The If-Modified-Since: date request field specifies
that the requested file should be sent only if it has been modified since the
given date.
 If the request has a body, the length of that body must be given with a
Content-length field, which gives the length of the response body in bytes.
POST method requests require this field because they send data to the
server.
 The header of a request must be followed by a blank line, which is used to
separate the header from the body of the request. Requests that use the
GET, HEAD, and DELETE methods do not have bodies. In these cases, the
blank line signals the end of the request.
 A browser is not necessary to communicate with a Web server; telnet can
be used instead. Consider the following command, given at the command
line of any widely used operating system:
> Telnet blanca.uccs.edu http
This command creates a connection to the http port on the
blanca.uccs.edu server.
The connection to the server is now complete, and HTTP commands
such as the following can be given:
GET /~user1/respond.html HTTP/1.1 Host:
blanca.uccs.edu
The Response Phase
The general form of an HTTP response is as follows:
1. Status line
2. Response header fields
3. Blank line
4. Response body
The status line includes the HTTP version used, a three-digit status code
for the response, and a short textual explanation of the status code. For
example, most responses begin with the following:

25
HTTP/1.1 200 OK
The status codes begin with 1, 2, 3, 4, or 5. The general meanings of the
five categories specified by these first digits are shown in Table 1.2.
Table 1.2 First digits of HTTP status codes
First Digit Category
1 Informational
2 Success
3 Redirection
4 Client error
5 Server error
One of the more common status codes is one user never want to see:
404 not found, which means the requested file could not be found. Of course,
200 OK is what users want to see, because it means that the request was
handled without error. The 500 code means that the server has encountered a
problem and was not able to fulfill the request.
After the status line, the server sends a response header, which can
contain several lines of information about the response, each in the form of a
field. The only essential field of the header is Content-type.
1.8 Origin and evaluation of HTML & XHTML
 At the onset, it is important to realize that XHTML is not a programming
language it cannot be used to describe computations. Its purpose is to
describe the general form and layout of documents to be displayed by a
browser.
 The word markup comes from the publishing world, where it is used to
describe what production people do with a manuscript to specify to a printer
how the text, graphics, and other elements in the book should appear in
printed form. XHTML is not the first markup language used with
computers. TeX and LaTeX are older markup languages for use with text;
they are now used primarily to specify how mathematical expressions and
formulas should appear in print.
 An XHTML document is a mixture of content and controls. The controls
are specified by the tags of XHTML. The name of a tag specifies the
category of its content. Most XHTML tags consist of a pair of syntactic
markers that are used to delimit particular kinds of content. The pair of tags
and their content together are called an element. For example, a paragraph
element specifies that its content, which appears between its opening tag,

26
<p>, and its closing tag, </p>, is a paragraph. A browser has a default style
(font, font style, font size, and so forth) for paragraphs, which is used to
display the content of a paragraph element.
 Some tags include attribute specifications that provide some additional
information for the browser. In the following example, the src attribute
specifies the location of the img tag’s image content:
<img src = "redhead.jpg"/>
In this case, the image document stored in the file redhead.jpg is to be
dis-played at the position in the document in which the tag appears. XHTML
1.0 was introduced in early 2000 by the W3C as an alternative to HTML 4.01,
which was at that time (and still is) the latest version of HTML. XHTML 1.0 is
nothing more than HTML 4.01 with stronger syntactic rules. The current
version, XHTML 1.1, was released in May 2001 as a replacement for XHTML
1.0, although, for various reasons, XHTML 1.0 is still widely used.
HTML vs XHTML
This specification defines an abstract language for describing
documents and applications, and some APIs for interacting with in-memory
representations of resources that use this language.
 The in-memory representation is known as "DOM HTML", or "the
DOM" for short. There are various concrete syntaxes that can be used to
transmit resources that use this abstract language, two of which are
defined in this specification.
 The first such concrete syntax is the HTML syntax. This is the format
suggested for most authors. It is compatible with most legacy Web
browsers. If a document is transmitted with the text/html MIME type,
then it will be processed as an HTML document by Web browsers. This
specification defines the latest HTML syntax, known simply as
"HTML".
 The second concrete syntax is the XHTML syntax, which is an
application of XML. When a document is transmitted with an XML
MIME type, such as application/xhtml+xml, then it is treated as an
XML document by Web browsers, to be parsed by an XML processor.
Authors are reminded that the processing for XML and HTML differs;
in particular, even minor syntax errors will prevent a document labeled
as XML from being rendered fully, whereas they would be ignored in
the HTML syntax. This specification defines the latest XHTML syntax,
known simply as "XHTML".

27
 The DOM, the HTML syntax, and the XHTML syntax cannot all
represent the same content. For example, namespaces cannot be
represented using the HTML syntax, but they are supported in the DOM
and in the XHTML syntax. Similarly, documents that use then
script feature can be represented using the HTML syntax, but cannot be
represented with the DOM or in the XHTML syntax. Comments that
contain the string "-->" can only be represented in the DOM, not in the
HTML and XHTML syntaxes.
XHTML document structure
This is the base frame of a XHTML document. It can be used as a
template for every new site.
<?xml version = “1.0” encoding = “utf-8″ ?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0
Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”&gt;
<!– This Is A Comment –>
<html xmlns = “http://www.w3.org/1999/xhtml”&gt;
<head>
<title>Put Title In Here</title>
</head>
<body>
This the Main Part
</body>
</html>
Every XHTML Documents needs this structure: Document Identification, html,
head and body whereas the head and body are inside the html tag.
Structure of an XHTML 1.0 Document:
 Elements and Tags
 Attributes
 Special Characters
 Comments
 A Complete XHTML 1.0 Document
 Validating your XHTML
Elements and Tags
 Elements are the structures that describe parts of an XHTML document. For
example, the p element represents a paragraph while the em element gives

28
emphasized content.
 An element has three parts: a start tag, content, and an end tag. A tag is
special text--"markup"--that is delimited by "<" and ">". An end tag
includes a "/" after the "<". For example, the em element has a start tag,
<em>, and an end tag, </em>. The start and end tags surround the content
of the em element:
<em>this is emphasized text</em>
 Element names must always be lower-case in XHTML, so <em> is allowed,
but <eM> and <EM> are not.
 Elements cannot overlap each other. If the start tag for an em element
appears within a p, the em's end tag must also appear within the same p
element.
Some elements have no content, so you don't have to type the full end tag.
These elements, such as the br element for line breaks, are represented only
by a start tag with a short-form closing tag as in <br />.
They are said to be empty.
Attributes
An element's attributes define various properties for the element. For
example, the ‘img’ element takes a ‘src’ attribute to provide the location of the
image and an alt attribute to give alternate text for those not loading images:
<img src="wdglogo.gif" alt="Web Design Group">
An attribute is included in the start tag only--never the end tag--and
takes the form attribute-name="Attribute-value". The attribute value is
delimited by single or double quotes.
Attribute names must be lower-case. Attribute values may be case-
sensitive.
Special Characters
 Certain characters in XHTML are reserved for use as markup and must
be escaped to appear literally. The "<" character may be represented
with an entity, &lt;. Similarly, ">" is escaped as &gt;, and "&" is
escaped as &amp;. If an attribute value contains a double quotation
mark and is delimited by double quotation marks, then the quote should
be escaped as &quot;.
 Other entities exist for special characters that cannot easily be entered
with some keyboards. For example, the copyright symbol ("©") may be
represented with the entity &copy;. See the Entities section for a
complete list of XHTML 1.0 entities.

29
 As an alternative to entities, authors may also use numeric character
references. Any character may be represented by a numeric character
reference based on its "code position" in Unicode. For example, one
could use &#169; for the copyright symbol or &#1575; for the Arabic
letter ALEF.
Comments
Comments in XHTML have a complicated syntax that can be simplified
by following this rule: Begin a comment with "<!--", end it with "-->", and do
not use "--" within the comment.
<!-- An example comment -->
A Complete XHTML 1.0 Document
An XHTML 1.0 document begins with a DOCTYPE declaration that
declares the version of XHTML to which the document conforms. The html
element follows and contains the head and body. The head contains information
about the document, such as its title and keywords, while the body contains the
actual content of the document, made up of block-level elements and inline
elements. A basic XHTML 1.0 document takes on the following form:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<Head>
<title>The document title</title>
</head>
<body>
<h1>Main heading</h1>
<p>A paragraph.</p>
<p>Another paragraph.</p>
<ul>
<li>A list item.</li>
<li>Another list item.</li>
</ul>
</body>
</html>
In a Frameset document, the frameset element replaces the body element.

30
Validating your XHTML
 Each XHTML document should be validated to check for errors such as
missing quotation marks (<a href="oops.html>Oops</a>), misspelled
element or attribute names, and invalid structures. Such errors are not
always apparent when viewing a document in a browser since browsers
are designed to recover from an author's errors. However, different
browsers recover in different ways, sometimes resulting in invisible text
on one browser but not on others.
 The WDG HTML Validator checks the validity of XHTML 1.0
documents.
Note that some programs claim to be validators but really are not. A
validator checks a document against a formal document type definition (DTD)
while other programs such as links warn about valid but unsafe XHTML. Both
kinds of programs are useful, but validation should never be forgotten.
1.9 Basic text markup
Phrase markup
Symbol HTML usage rendering
_ (underscore) emphasis <em> _sample sample text
text_
* strong <strong> *sample sample text
text*
__ italics <i> __sample sample text
text__
** bold <bold> **sample sample text
text*
- (hyphen) strikethrough <del> -sample text-
+ inserted <ins> +sample sample text
text+
^ superscript <sup> sample sample text
^text^
~ (tilde) subscript <sub> sample sample text
~text~
@ code <code> @sample sample text
text@
== no mod n/a ==sample sample text
text==

31
% span <span> %sample sample text
text%
++ bigger <big> ++sample sample text
text++
-- smaller <small> --sample sample text
text--
See the phrase markup category in the example browser.
The symbols in the table are used to mark phrases within a block and
correspond to inline HTML tags.
Note the %, <span>, can take modifiers like a signature does.
Example:
The care of human life and happiness, and *not* their destruction,
Is the first and only object of good government %{color:red} (Thomas
Jefferson)
<p>the <em>care</em> of human life and happiness, and
<strong>not</strong> their destruction, is the first and only object of
Good government. <span style="color:red;padding-left:2em;">Thomas
Jefferson</span></p>
The care of human life and happiness, and not their destruction, is the
first and only object of good government. Thomas Jefferson
1.10 Hypertext Links
Markup HTML

"text":url Link <a href="url">text</a>

"text(title text)":url link with title <a href="url" title="title


text text">text</a>

!url! Image <img src="url" />

!url(alternate text)! image with <img src="url" alt="alternate


alternate text text" title="alternate text" />

!imgURL!:url linked image <a href="url"><img


src="imgURL" /></a>

!imgURL(alt linked image <a href="url"><img


text)!:url with alternate src="imgURL" alt="alt text"
text title="alt text" /></a>

32
Link and image markup are a form of phrase markup with a little structure
added.
See the links and images category in the example browser.
See also URL abbreviations in the directives chapter if you find yourself using
the same URL many places in your project.
The < and > modifiers when applied to images cause them to float.
Examples
Simple link:
See "here":topics.html for the Xilize2 User Guide.
<p>See <a href ="topics.html">here</a> for the Xilize2 User Guide. </p>
See here for the Xilize2 User Guide.
Link with title:
See "here (Xilize2 User Guide)":topics.html for the same link with title text.
<p>See <a href="topics.html" title="Xilize2 User Guide">here</a> for
The same link with title text.</p>
See here for the same link with title text.
Simple image:
This! . ./images/xilbox.png! is a common image on this site.
<p>This <img src="../images/xilbox.png" /> is a common image on this
site.</p>
This is a common image on this site.
Image with alt and title:
This is the same image !../images/xilbox.png (Xilize document list)!
with @alt@ and @title@ attributes set.
<p>This is the same image <img src="../images/xilbox.png" alt="Xilize
Document list" title="Xilize document list" /> with <code>alt</code> and
<code>title</code> attributes set.</p>
This is the same image with alt and title attributes set.

33
1.11 Lists
markup Description

* item top-level unordered list

** item 2nd-level unordered list

# item top-level ordered list

## item 2nd-level ordered list

dl. term : def definition list

See the lists & definition list categories in the example browser.
The example browser shows how basic list markup works. This
example shows how modifiers can be applied to lists and list items (and shows
that list types can be mixed):
{color: purple}* item 1
** Item 1a
**{color: brown} item 1b
*** item 1b1
* item 3
* item 4
## item 5
## item 6
<ul style="color:purple;">
<li>item 1
<ul>
<li>item 1a</li>
<li style="color:brown;">item 1b
<ul>
<li>item 1b1</li>
</ul>
</li>
</ul>
</li>
<li>item 3</li>
<li>item 4

34
<Ol>
<li>item 5</li>
<li>item 6</li>
</ol>
</li>
</ul>
 item 1
o item 1a
o item 1b
 item 1b1
 item 3
 item 4
o item 5
o item 6
1.12 Tables
See the tables category in the example browser.
The example browser shows how basic table markup works. Notice
the table. Signature is required only when applying modifiers to an entire table;
otherwise Xilize recognizes a block in which each line begins with a | (vertical
bar) as indicating a table.
 each line of a table block is taken to be a row in the table
 Xilize is aware of table headers <thead> and footers <tfoot> as well as
column groups —<colgroup> and <col>
 row, cells, and the entire table may have modifiers, note that cell
modifiers end with a .(dot/period)
Table header and footer rows
Here is a table with header and footer rows with row and cell modifiers:
_| h1 |{background:#ddf} 1
_| h2 | 2
|a|3
{color:orange}| b | 4
|c|5
_| f1 | 6
<table>
<thead>

35
<tr>
<td>h1</td>
<td style="background:#ddf;"> 1</td>
</tr>
<tr>
<td>h2</td>
<td>2</td>
</tr>
</thead>
<tfoot>
<tr>
<td>f1</td>
<td>6</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>a</td>
<td>3</td>
</tr>
<tr style="color:orange;">
<td>b</td>
<td>4</td>
</tr>
<tr>
<td>c</td>
<td>5</td>
</tr>
</tbody>
</table>
Here is the resulting table. Note that the external CSS style sheet for this
User Guide adds a gray background to table header and footer rows and adds
borders to the cells.

36
h1 1

h2 2

f1 6

a 3

b 4

c 5

Markup for <colgroup> & <col>


See also the W3C spec for colgroup.
The HTML elements <colgroup> & <col> provide a way to group and
style table columns. The corresponding Xilize markup uses a special syntax —
&amp;{columns: ... } — with the explicit table.signature:
Table. &amp ;{ columns:
\2{background:lightblue}
\4{background:lightgreen}
\3{background:lightyellow}
}
|1|2|3|4|5|6|7|8|9
|1|2|3|4|5|6|7|8|9
<Table>
<colgroup span="2" style="background:lightblue;" />
<colgroup span="4" style="background:lightgreen;" />
<colgroup span="3" style="background:lightyellow;" />
<Tbody>
<TR>
<Td>1</td>
<Td>2</td>
...

1 2 3 4 5 6 7 8 9

1 2 3 4 5 6 7 8 9

37
Colgroup with <col> tags
Each line within &amp ;{ columns:...} markup translates to
a <colgroup> element. If cells — marked by the | (vertical bar) just like table
cells — are present on the line, they are translated to <col>elements.
In this example the first two column groups contain column elements
and third does not:
.table. &amp;{columns:
| 50 |{background:lightblue} 40
{background:lightgreen}| | 80 | |
\3{background:lightyellow} 30
}
|1|2|3|4|5|6|7|8|9
|1|2|3|4|5|6|7|8|9
<Table>
<Colgroup>
<col width="50" />
<col width="40" style="background: lightblue;" />
</colgroup>
<colgroup style="background: lightgreen;">
<col />
<col width="80" />
<col />
<col />
</colgroup>
<colgroup span="3" width="30" style="background: lightyellow;" />
<Tbody>
<TR>
<Td>1</td>
<td>2</td>
...

1 2 3 4 5 6 7 8 9

1 2 3 4 5 6 7 8 9

38
Footnotes

markup description

text[1] footnote marker, 1 may be any number, use this markup in


your text, repeat with different numbers as needed

fn1. body of footnote text, 1 may be any number, this is a block signature,
footnote repeat with different numbers as needed

Footnotes are marked with [1] and the text of the footnote is given with
the footnote signature, fn1. Where 1 can be any number. Xilize creates anchors
and links between the two and allows you to choose to have
the HTML generated with or without <sup> tags.
1.13 Forms
 HTML Forms are required when you want to collect some data from
the site visitor. For example during user registration you would like to
collect information such as name, email address, credit card, etc.
 A form will take input from the site visitor and then will post it to a
back-end application such as CGI, ASP Script or PHP script etc. The
back-end application will perform required processing on the passed
data based on defined business logic inside the application.
 There are various form elements available like text fields, text area
fields, drop-down menus, radio buttons, checkboxes, etc.
The HTML <form> tag is used to create an HTML form and it has
following syntax:
<form action="Script URL" method="GET|POST">
form elements like input, text area etc.
</form>
Example
An HTML form with two input fields and one submit button:
<form action="demo_form.asp" method="get">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
Definition and Usage
The <form> tag is used to create an HTML form for user input.
The <form> element can contain one or more of the following form elements:

39
 <input>
 <textarea>
 <button>
 <select>
 <option>
 <optgroup>
 <fieldset>
 <label>
Attributes

Attribute Value Description

accept file_type Not supported in HTML5.


Specifies a comma-separated list of file
types that the server accepts (that can be
submitted through the file upload)

accept-charset character_set Specifies the character encodings that are


to be used for the form submission

action URL Specifies where to send the form-data


when a form is submitted

autocomplete on Specifies whether a form should have


off autocomplete on or off

enctype application/x- Specifies how the form-data should be


www-form- encoded when submitting it to the server
urlencoded (only for method="post")
multipart/form-
data
text/plain

method get Specifies the HTTP method to use when


post sending form-data

name text Specifies the name of a form

40
novalidate novalidate Specifies that the form should not be
validated when submitted

target _blank Specifies where to display the response


_self that is received after submitting the form
_parent
_top

1.14 Frames
Creating Frames
To use frames on a page we use <frameset> tag instead of <body> tag.
The <frameset> tag defines how to divide the window into frames. The rows
attribute of <frameset> tag defines horizontal frames and cols attribute defines
vertical frames. Each frame is indicated by <frame> tag and it defines which
HTML document shall open into the frame.
Example
Following is the example to create three horizontal frames:
<!DOCTYPE html>
<html>
<head>
<title>HTML Frames</title>
</head>
<frameset rows="10%,80%,10%">
<frame name="top" src="/html/top_frame.htm" />
<frame name="main" src="/html/main_frame.htm" />
<frame name="bottom" src="/html/bottom_frame.htm" />
<Noframes>
<Body>
Your browser does not support frames.
</body>
</noframes>
</frameset>
</html>

41
This will produce following result:

Example
Let's put above example as follows, here we replaced rows attribute by
cols and changed their width. This will create all the three frames vertically:
<!DOCTYPE html>
<html>
<head>
<title>HTML Frames</title>
</head>
<frameset cols="25%,50%,25%">
<frame name="left" src="/html/top_frame.htm" />
<frame name="center" src="/html/main_frame.htm" />
<frame name="right" src="/html/bottom_frame.htm" />
<noframes>
<body>
Your browser does not support frames.
</body>
</noframes>
</frameset>
</html>
This will produce following result:

42
The <frameset> Tag Attributes
Following are important attributes of the <frameset> tag:

Attribute Description

cols Specifies how many columns are contained in the frameset and
the size of each column. You can specify the width of each
column in one of four ways:
 Absolute values in pixels. For example to create three
vertical frames, use cols="100, 500,100".
 A percentage of the browser window. For example to
create three vertical frames, use cols="10%, 80%,10%".
 Using a wildcard symbol. For example to create three
vertical frames, use cols="10%, *,10%". In this case
wildcard takes remainder of the window.
 As relative widths of the browser window. For example
to create three vertical frames, usecols="3*,2*,1*". This
is an alternative to percentages. You can use relative
widths of the browser window. Here the window is
divided into sixths: the first column takes up half of the
window, the second takes one third, and the third takes
one sixth.

rows This attribute works just like the cols attribute and takes the
same values, but it is used to specify the rows in the frameset.
For example to create two horizontal frames, use rows="10%,
90%". You can specify the height of each row in the same way
as explained above for columns.

border This attribute specifies the width of the border of each frame in
pixels. For example border="5". A value of zero means no
border.

Frame This attribute specifies whether a three-dimensional border


border should be displayed between frames. This attrubute takes value
either 1 (yes) or 0 (no). For example frameborder="0" specifies
no border.

43
Frame This attribute specifies the amount of space between frames in
spacing a frameset. This can take any integer value. For example
framespacing="10" means there should be 10 pixels spacing
between each frames.

The <frame> Tag Attributes


Following are important attributes of <frame> tag:

Attribute Description

src This attribute is used to give the file name that should be loaded
in the frame. Its value can be any URL. For example,
src="/html/top_frame.htm" will load an HTML file available in
html directory.

name This attribute allows you to give a name to a frame. It is used to


indicate which frame a document should be loaded into. This is
especially important when you want to create links in one
frame that load pages into an another frame, in which case the
second frame needs a name to identify itself as the target of the
link.

frameborder This attribute specifies whether or not the borders of that frame
are shown; it overrides the value given in the frameborder
attribute on the <frameset> tag if one is given, and this can take
values either 1 (yes) or 0 (no).

marginwidth This attribute allows you to specify the width of the space
between the left and right of the frame's borders and the frame's
content. The value is given in pixels. For example
marginwidth="10".

marginheight This attribute allows you to specify the height of the space
between the top and bottom of the frame's borders and its
contents. The value is given in pixels. For example
marginheight="10".

44
noresize By default you can resize any frame by clicking and dragging
on the borders of a frame. The noresize attribute prevents a user
from being able to resize the frame. For example
noresize="noresize".

scrolling This attribute controls the appearance of the scrollbars that


appear on the frame. This takes values either "yes", "no" or
"auto". For example scrolling="no" means it should not have
scroll bars.

longdesc This attribute allows you to provide a link to another page


containing a long description of the contents of the frame. For
example longdesc="framedescription.htm"

1.16 Syntactic differences between HTML & XHTML


HTML and XHTML are both languages in which web pages are
written. HTML is SGML-based while XHTML is XML-based. They are like
two sides of the same coin. XHTML was derived from HTML to conform to
XML standards. Hence XHTML is strict when compared to HTML and does
not allow user to get away with lapses in coding and structure.
The reason for XHTML to be developed was convoluted browser
specific tags. Pages coded in HTML appeared different in different browsers.
Comparison chart
HTML XHTML
Introduction HTML or Hyper Text XHTML (Extensible Hyper
Markup Language is the Text Markup Language) is a
main markup language for family of XML markup
creating web pages and languages that mirror or
other information that can extend versions of the widely
be displayed in a web used Hypertext Markup
browser. Language (HTML), the
language in which web pages
are written.
Filename .html, .htm .xhtml, .xht, .xml, .html, .htm
extension
Internet text/html application/xhtml+xml
media type

45
Developed W3C & WHATWG World Wide Web Consortium
by

Type of Document file format Markup language


format
Extended SGML XML, HTML
from
Stands Hyper Text Markup Extensible Hyper Text
Language Markup Language
Function Web pages are written in Extended version of HTML
HTML. that is stricter and XML-
based.
Nature Flexible framework Restrictive subset of XML
requiring lenient HTML and needs to be parsed with
specific parser. standard XML parsers.
Origin Proposed by Tim Berners- World Wide Web Consortium
Lee in 1987. Recommendation in 2000.
Application Application of Standard Application of XML
Generalized Markup
Language (SGML).
Versions HTML 2, HTML 3.2, XHTML 1, XHTML 1.1,
HTML 4.0, HTML 5. XHTML 2, XHTML 5.
Contents: HTML vs XHTML
1 Overview of HTML and XHTML
2 Features of HTML vs XHTML documents
3 XHTML vs HTML Specification
4 How to migrate from HTML to XHTML
5 How to migrate from XHTML to HTML
6 References
Overview of HTML and XHTML
 HTML is the predominant markup language for web pages. HTML
creates structured documents by denoting structural semantics for text
like headings, lists, links, quotes etc. It allows images and objects to be
embedded to create interactive forms.

46
 It is written as tags surrounded by angle brackets - for example, <html>.
Scripts in languages like JavaScript can also be loaded.
 XHTML is a family of XML languages which extend or mirror versions
of HTML. It does not allow omission of any tags or use of attribute
minimization.
 XHTML requires that there be an end tag to every start tag and all
nested tags must be closed in the right order. For example, while <br> is
valid in HTML, it would be required to write <br /> in XHTML.
Features of HTML vs XHTML documents
 HTML documents are composed of elements that have three
components- a pair of element tags – start tag, end tag; element
attributes given within tags and actual, textual and graphic content.
HTML element is everything that lies between and including tags. (Tag
is a keyword which is enclosed within angle brackets).
 XHTML documents has only one root element. All elements including
variables must be in lower case, and values assigned must be surrounded
by quotation marks, closed and nested for being recognized. This is a
mandatory requirement in XHTML unlike HTML where it is optional.
The declaration of DOCTYPE would determine rules for documents to
follow.
Aside from the different opening declarations for a document, the
differences between an HTML 4.01 and XHTML 1.0 document—in each of the
corresponding DTDs—are largely syntactic. The underlying syntax of HTML
allows many shortcuts that XHTML does not, such as elements with optional
opening or closing tags, and even EMPTY elements which must not have an
end tag. By contrast, XHTML requires all elements to have an opening tag or a
closing tag. XHTML, however, also introduces a new shortcut: an XHTML tag
may be opened and closed within the same tag, by including a slash before the
end of the tag like this: <br/>. The introduction of this shorthand, which is not
used in the SGML declaration for HTML 4.01, may confuse earlier software
unfamiliar with this new convention. A fix for this is to include a space before
closing the tag, as such: <br />.
XHTML vs HTML Specification
HTML and XHTML are closely related and therefore can be
documented together. Both HTML 4.01 and XHTML 1.0 have three sub
specifications – strict, loose and frameset. The difference opening declarations
for a document distinguishes HTML and XHTML. Other differences are
syntactic. HTML allows shortcuts like elements with optional tags, empty

47
elements without end tags. XHTML is very strict about opening and closing
tags. XHTML uses built in language defining functionality attribute. All syntax
requirements of XML are included in a well formed XHTML document.
Note, though, that these differences apply only when an XHTML
document is served as an application of XML; that is, with a MIME type of
application/xhtml+xml, application/xml, or text/xml. An XHTML document
served with a MIME type of text/html must be parsed and interpreted as
HTML, so the HTML rules apply in this case. A style sheet written for an
XHTML document being served with a MIME type of text/html may not work
as intended if the document is then served with a MIME type of
application/xhtml+xml. For more information about MIME types, make sure to
read MIME Types.
This can be especially important when you’re serving XHTML
documents as text/html. Unless you’re aware of the differences, you may create
style sheets that won’t work as intended if the document’s served as real
XHTML. Where the terms “XHTML” and “XHTML document” appear in the
remainder of this section, they refer to XHTML markup served with an XML
MIME type. XHTML markup served as text/html is an HTML document as far
as browsers are concerned.
How to migrate from HTML to XHTML
As following steps can be followed for migration of HTML to XHTML
(XHTML 1.0 documents):
 Include xml:lang and lang attributes on elements assigning language.
 Use empty-element syntax on elements specified as empty in HTML.
 Include an extra space in empty-element tags: <html />
 Include close tags for elements that can have content but are empty:
<html></html>
 Do not include XML declaration.
A user agent (web browser) should be able to interpret documents with
equal ease as HTML or XHTML.
How to migrate from XHTML to HTML
To understand the subtle differences between HTML and XHTML,
consider the transformation of a valid and well-formed XHTML 1.0 document
into a valid HTML 4.01 document. To make this translation requires the
following steps:

48
 The language for an element should be specified with a lang attribute
rather than the XHTML xml:lang attribute. XHTML uses XML's built
in language-defining functionality attribute.
 Remove the XML namespace (xmlns=URI). HTML has no facilities for
namespaces.
 Change the document type declaration from XHTML 1.0 to HTML
4.01.
 If present, remove the XML declaration. (Typically this is: <?xml
version="1.0" encoding="utf-8"?>).
 Ensure that the document’s MIME type is set to text/html. For both
HTML and XHTML, this comes from the HTTP Content-Type header
sent by the server.
 Change the XML empty-element syntax to an HTML style empty
element (<br/> to <br>).

49
NOTES
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………

50
UNIT – II

CASCADING STYLE SHEET


In This Chapter
 Introduction Cascading Style Sheet (CSS)
 Overview of Java Script
 Object Orientation and Java Script
 Primitives, Operation and Expressions
 Screen Output and Keyboard Input
 Control Statements
 Object Creation Modifications, Arrays
 Function Construction
 Pattern matching using Regular expression
2.1 Introduction Cascading Style Sheet (CSS)
A cascading style sheet (CSS) is a Web page derived from multiple
sources with a defined order of precedence where the definitions of any style
element conflict. The Cascading Style Sheet, level 1 (CSS1) recommendation
from the World Wide Web Consortium (W3C), which is implemented in the
latest versions of the Netscape and Microsoft Web browsers, specifies the
possible style sheets or statements that may determine how a given element is
presented in a Web page. CSS gives more control over the appearance of a Web
page to the page creator than to the browser designer or the viewer. With CSS,
the sources of style definition for a given document element are in this order of
precedence:
1. The STYLE attribute on an individual element tag
2. The STYLE element that defines a specific style sheet containing style
declarations or a LINK element that links to a separate document
containing the STYLE element. In a Web page, the STYLE element is
placed between the TITLE statement and the BODY statement.
3. An imported style sheet, using the CSS @import notation to automatically
import and merge an external style sheet with the current style sheet
4. Style attributes specified by the viewer to the browser
5. The default style sheet assumed by the browser
Introduction to style sheets
Style sheets represent a major breakthrough for Web page designers,
expanding their ability to improve the appearance of their pages. In the

51
scientific environments in which the Web was conceived, people are more
concerned with the content of their documents than the presentation. As people
from wider walks of life discovered the Web, the limitations of HTML became
a source of continuing frustration and authors were forced to sidestep HTML's
stylistic limitations. While the intentions have been good to improve the
presentation of Web pages the techniques for doing so have had unfortunate
side effects. These techniques work for some of the people, some of the time,
but not for all of the people, all of the time. They include:
 Using proprietary HTML extensions
 Converting text into images
 Using images for white space control
 Use of tables for page layout
 Writing a program instead of using HTML
These techniques considerably increase the complexity of Web pages,
offer limited flexibility, suffer from interoperability problems, and create
hardships for people with disabilities. Style sheets solve these problems at the
same time they supersede the limited range of presentation mechanisms in
HTML. Style sheets make it easy to specify the amount of white space between
text lines, the amount lines are indented, the colors used for the text and the
backgrounds, the font size and style, and a host of other details.
For example the following short CSS style sheet (stored in the file
"special.css") sets the text color of a paragraph to green and surrounds it with a
solid red border:
P.special {
color : green;
border: solid red;
}
Authors may link this style sheet to their source HTML document with
the LINK element:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<LINK href="special.css" rel="stylesheet" type="text/css">
</HEAD>
<BODY>

52
<P class="special">this paragraph should have special green text.
</BODY>
</HTML>
HTML 4 provides support for the following style sheet features:
Cascading
This is the capability provided by some style sheet languages such as
CSS to allow style information from several sources to be blended together.
These could be, for instance, corporate style guidelines, styles common to a
group of documents, and styles specific to a single document. By storing these
separately, style sheets can be reused, simplifying authoring and making more
effective use of network caching. The cascade defines an ordered sequence of
style sheets where rules in later sheets have greater precedence than earlier
ones. Not all style sheet languages support cascading.
Media dependencies
HTML allows authors to specify documents in a media-independent
way. This allows users to access Web pages using a wide variety of devices and
media, e.g., graphical displays for computers running Windows, Macintosh OS,
and X11, devices for television sets, specially adapted phones and PDA-based
portable devices, speech-based browsers, and braille-based tactile devices.
Style sheets, by contrast, apply to specific media or media groups. A
style sheet intended for screen use may be applicable when printing, but is of
little use for speech-based browsers. This specification allows you to define the
broad categories of media a given style sheet is applicable to. This allows user
agents to avoid retrieving inappropriate style sheets. Style sheet languages may
include features for describing media dependencies within the same style sheet.
Alternate styles
Authors may wish to offer readers several ways to view a document.
For instance, a style sheet for rendering compact documents with small fonts,
or one that specifies larger fonts for increased legibility. This specification
allows authors to specify a preferred style sheet as well as alternates that target
specific users or media. User agents should give users the opportunity to select
from among alternate style sheets or to switch off style sheets altogether.
Performance concerns
Some people have voiced concerns over performance issues for style
sheets. For instance, retrieving an external style sheet may delay the full
presentation for the user. A similar situation arises if the document head
includes a lengthy set of style rules.

53
The current proposal addresses these issues by allowing authors to
include rendering instructions within each HTML element. The rendering
information is then always available by the time the user agent wants to render
each element.
In many cases, authors will take advantage of a common style sheet for
a group of documents. In this case, distributing style rules throughout the
document will actually lead to worse performance than using a linked style
sheet, since for most documents, the style sheet will already be present in the
local cache. The public availability of good style sheets will encourage this
effect.
Adding style to HTML
HTML documents may contain style sheet rules directly in them or they
may import style sheets. Any style sheet language may be used with HTML. A
simple style sheet language may suffice for the needs of most users, but other
languages may be more suited to highly specialized needs. This specification
uses the style language "Cascading Style Sheets" (CSS1), abbreviated CSS, for
examples.
The syntax of style data depends on the style sheet language.
Setting the default style sheet language
Authors must specify the style sheet language of style information
associated with an HTML document.
Authors should use the META element to set the default style sheet language
for a document. For example, to set the default to CSS, authors should put the
following declaration in the HEAD of their documents:
<META http-equiv="Content-Style-Type" content="text/css">
The default style sheet language may also be set with HTTP headers.
The above META declaration is equivalent to the HTTP header:
Content-Style-Type: text/css
User agents should determine the default style sheet language for a
document according to the following steps (highest to lowest priority):
1. If any META declarations specify the "Content-Style-Type", the last
one in the character stream determines the default style sheet language.
2. Otherwise, if any HTTP headers specify the "Content-Style-Type", the
last one in the character stream determines the default style sheet
language.
3. Otherwise, the default style sheet language is "text/css".

54
Documents that include elements that set the style attribute but which
don't define a default style sheet language are incorrect. Authoring tools should
generate default style sheet language information (typically
a META declaration) so that user agents do not have to rely on a default of
"text/css".
Attribute definitions
Style = style [CN]
Type = content-type [CI]
Media = media-descriptors [CI]
Media types
HTML allows authors to design documents that take advantage of the
characteristics of the media where the document is to be rendered (e.g.,
graphical displays, television screens, handheld devices, speech-based
browsers, braille-based tactile devices, etc.). By specifying the media attribute,
authors allow user agents to load and apply style sheets selectively. Please
consult the list of recognized media descriptors.
The following sample declarations apply to H1 elements. When
projected in a business meeting, all instances will be blue. When printed, all
instances will be centered.
<HEAD>
<STYLE type="text/css" media="projection">
H1 {color: blue}
</STYLE>
<STYLE type="text/css" media="print">
H1 {text-align: center}
</STYLE>
This example adds sound effects to anchors for use in speech output:
<STYLE type="text/css" media="aural">
A {cue-before: uri(bell.aiff); cue-after: uri(dong.wav)}
</STYLE>
</HEAD>
Media control is particularly interesting when applied to external style
sheets since user agents can save time by retrieving from the network only
those style sheets that apply to the current device. For instance, speech-based
browsers can avoid downloading style sheets designed for visual rendering. See
the section on media-dependent cascades for more information.

55
External style sheets
Authors may separate style sheets from HTML documents. This offers
several benefits:
 Authors and Web site managers may share style sheets across a number
of documents (and sites).
 Authors may change the style sheet without requiring modifications to
the document.
 User agents may load style sheets selectively (based on media
descriptions).
Preferred and alternate style sheets
HTML allows authors to associate any number of external style sheets
with a document. The style sheet language defines how multiple external style
sheets interact (for example, the CSS "cascade" rules).
Authors may specify a number of mutually exclusive style sheets
called alternate style sheets. Users may select their favorite among these
depending on their preferences. For instance, an author may specify one style
sheet designed for small screens and another for users with weak vision (e.g.,
large fonts). User agents should allow users to select from alternate style sheets.
The author may specify that one of the alternates is a preferred style
sheet. User agents should apply the author's preferred style sheet unless the user
has selected a different alternate.
Authors may group several alternate style sheets (including the author's
preferred style sheets) under a single style name. When a user selects a named
style, the user agent must apply all style sheets with that name. User agents
must not apply alternate style sheets with a different style name. The section
on specifying external style sheets explains how to name a group of style
sheets.
Authors may also specify persistent style sheets that user agents must
apply in addition to any alternate style sheet.
User agents must respect media descriptors when applying any style
sheet.
User agents should also allow users to disable the author's style sheets
entirely, in which case the user agent must not apply any persistent or alternate
style sheets.
Specifying external style sheets
Authors specify external style sheets with the following attributes of
the LINK element:

56
 Set the value of href to the location of the style sheet file. The value
of href is a URI.
 Set the value of the type attribute to indicate the language of the linked
(style sheet) resource. This allows the user agent to avoid downloading
a style sheet for an unsupported style sheet language.
 Specify that the style sheet is persistent, preferred, or alternate:
o To make a style sheet persistent, set the rel attribute to
"stylesheet" and don't set the title attribute.
o To make a style sheet preferred, set the rel attribute to
"stylesheet" and name the style sheet with the title attribute.
o To specify an alternate style sheet, set the rel attribute to
"alternate stylesheet" and name the style sheet with
thetitle attribute.
Cascading style sheets
Cascading style sheet languages such as CSS allow style information
from several sources to be blended together. However, not all style sheet
languages support cascading. To define a cascade, authors specify a sequence
of LINK and/or STYLE elements. The style information is cascaded in the
order the elements appear in the HEAD.
In the following example, we specify two alternate style sheets named
"compact". If the user selects the "compact" style, the user agent must apply
both external style sheets, as well as the persistent "common.css" style sheet. If
the user selects the "big print" style, only the alternate style sheet "bigprint.css"
and the persistent "common.css" will be applied.
<LINK rel="alternate stylesheet" title="compact" href="small-base.css"
type="text/css">
<LINK rel="alternate stylesheet" title="compact" href="small-extras.css"
type="text/css">
<LINK rel="alternate stylesheet" title="big print" href="bigprint.css"
type="text/css">
<LINK rel="stylesheet" href="common.css" type="text/css">
Here is a cascade example that involves both the LINK and STYLE elements.
<LINK rel="stylesheet" href="corporate.css" type="text/css">
<LINK rel="stylesheet" href="techreport.css" type="text/css">
<STYLE type="text/css">
p.special {color: rgb(230, 100, 180) }
</STYLE>

57
2.2 Overview of JavaScript
JavaScript is a dynamic computer programming language. It is
lightweight and most commonly used as a part of web pages, whose
implementations allow client-side script to interact with the user and make
dynamic pages. It is an interpreted programming language with object-
oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its
name to JavaScript, possibly because of the excitement being generated by
Java. JavaScript made its first appearance in Netscape 2.0 in 1995 with the
name LiveScript. The general-purpose core of the language has been
embedded in Netscape, Internet Explorer, and other web browsers.
The ECMA-262 Specification defined a standard version of the core
JavaScript language.
 JavaScript is a lightweight, interpreted programming language.
 Designed for creating network-centric applications.
 Complementary to and integrated with Java.
 Complementary to and integrated with HTML.
 Open and cross-platform
Client-side Java Script
Client-side JavaScript is the most common form of the language. The
script should be included in or referenced by an HTML document for the code
to be interpreted by the browser.
It means that a web page need not be a static HTML, but can include
programs that interact with the user, control the browser, and dynamically
create HTML content.
The JavaScript client-side mechanism provides many advantages over
traditional CGI server-side scripts. For example, you might use JavaScript to
check if the user has entered a valid e-mail address in a form field.
The JavaScript code is executed when the user submits the form, and
only if all the entries are valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button
clicks, link navigation, and other actions that the user initiates explicitly or
implicitly.

58
Advantages of JavaScript
The merits of using JavaScript are
 Less server interaction You can validate user input before sending
the page off to the server. This saves server traffic, which means less
load on your server.
 Immediate feedback to the visitors They don't have to wait for a
page reload to see if they have forgotten to enter something.
 Increased interactivity You can create interfaces that react when the
user hovers over them with a mouse or activates them via the
keyboard.
 Richer interfaces You can use JavaScript to include such items as
drag-and-drop components and sliders to give a Rich Interface to your
site visitors.
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It
lacks the following important features
 Client-side JavaScript does not allow the reading or writing of files.
This has been kept for security reason.
 JavaScript cannot be used for networking applications because there is
no such support available.
 JavaScript doesn't have any multithreading or multiprocessor
capabilities.
Once again, JavaScript is a lightweight, interpreted programming
language that allows you to build interactivity into otherwise static HTML
pages.
JavaScript Development Tools
One of major strengths of JavaScript is that it does not require
expensive development tools. You can start with a simple text editor such as
Notepad. Since it is an interpreted language inside the context of a web
browser, you don't even need to buy a compiler.
To make our life simpler, various vendors have come up with very nice
JavaScript editing tools. Some of them are listed here
 Microsoft FrontPage Microsoft has developed a popular HTML
editor called FrontPage. FrontPage also provides web developers with
a number of JavaScript tools to assist in the creation of interactive
websites.

59
 Macromedia Dreamweaver MX Macromedia Dreamweaver MX is a
very popular HTML and JavaScript editor in the professional web
development crowd. It provides several handy prebuilt JavaScript
components, integrates well with databases, and conforms to new
standards such as XHTML and XML.
 Macromedia HomeSite 5 HomeSite 5 is a well-liked HTML and
JavaScript editor from Macromedia that can be used to manage
personal websites effectively.
 JavaScript syntax is the set of rules, how JavaScript programs are
constructed.
 JavaScript Programs
 A computer program is a list of "instructions" to be "executed" by the
computer.
 In a programming language, these program instructions are
called statements.
 JavaScript is a programming language.
 JavaScript statements are separated by semicolons.
Example
var x = 5;
var y = 6;
var z = x + y;
JavaScript Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
JavaScript Values
The JavaScript syntax defines two types of values: Fixed values and variable
values.
Fixed values are called literals. Variable values are called variables.
JavaScript Literals
The most important rules for writing fixed values are:
Numbers are written with or without decimals:
10.50
1001
2.3 Object-oriented and Java Script programming
Object-oriented programming (OOP) is a programming language model
organized around "objects" rather than "actions" and data rather than logic.

60
The programming challenge was seen as how to write the logic, not how
to define the data. Object-oriented programming takes the view that what we
really care about are the objects we want to manipulate rather than the logic
required to manipulate them. Examples of objects range from human beings
(described by name, address, and so forth) to buildings and floors (whose
properties can be described and managed) down to the little widgets on a
computer desktop (such as buttons and scroll bars).
The first step in OOP is to identify all the objects the programmer wants
to manipulate and how they relate to each other, an exercise often known as
data. Once an object has been identified, it is generalized as a class of objects
(think of Plato's concept of the "ideal" chair that stands for all chairs) which
defines the kind of data it contains and any logic sequences that can manipulate
it. Each distinct logic sequence is known as a method. Objects communicate
with well-defined interfaces called messages.
The concepts and rules used in object-oriented programming provide
these important benefits:
 The concept of a data class makes it possible to define subclasses of data
objects that share some or all of the main class characteristics.
Called inheritance, this property of OOP forces a more thorough data
analysis, reduces development time, and ensures more accurate coding.
 Since a class defines only the data it needs to be concerned with, when an
instance of that class (an object) is run, the code will not be able to
accidentally access other program data. This characteristic of data
hiding provides greater system security and avoids unintended data
corruption.
 The definition of a class is reuseable not only by the program for which it is
initially created but also by other object-oriented programs (and, for this
reason, can be more easily distributed for use in networks).
 The concept of data classes allows a programmer to create any new data
type that is not already defined in the language itself.
Simula was the first object-oriented programming language.
Java, Python,C++, Visual Basic .NET and Ruby are the most popular OOP
languages today. The Java programming language is designed especially for
use in distributed applications on corporate networks and the Internet. Ruby is
used in many Web applications. Curl, Smalltalk, Delphi and Eiffel are also
examples of object-oriented programming languages.

61
JavaScript
JavaScript is a programming language commonly used in web
development. It was originally developed by Netscape as a means to add
dynamic and interactive elements to websites. While JavaScript is influenced
by Java, the syntax is more similar to C and is based on ECMA Script, a
scripting language developed by Sun Microsystems.
JavaScript is a client-side scripting language, which means the source
code is processed by the client's web browser rather than on the web server.
This means JavaScript functions can run after a webpage has loaded without
communicating with the server. For example, a JavaScript function may check
a web form before it is submitted to make sure all the required fields have been
filled out. The JavaScript code can produce an error message before any
information is actually transmitted to the server.
Like server-side scripting languages, such as PHP and ASP, JavaScript
code can be inserted anywhere within the HTML of a webpage. However, only
the output of server-side code is displayed in the HTML, while JavaScript code
remains fully visible in the source of the webpage. It can also be referenced in a
separate .JS file, which may also be viewed in a browser.
Below is an example of a basic JavaScript function that adds two
numbers. The function is called with the parameters 7 and 11. If the code below
were included in the HTML of a webpage, it would display the text “18” in
an alert box.
<script>
function sum(a, b)
{
return a + b;
}
var total = sum(7,11);
alert(total);
</script>
JavaScript functions can be called within <script> tags or when specific
events take place. Examples include onClick, onMouseDown, onMouseUp,
onKeyDown, onKeyUp, onFocus, onBlur, onSubmit, and many others.
While standard JavaScript is still used for performing basic client-side
functions, many web developers now prefer to use JavaScript libraries
like jQuery to add more advanced dynamic elements to websites.
JavaScript can be implemented using JavaScript statements that are
placed within the <script>... </script> HTML tags in a web page.

62
You can place the <script> tags, containing your JavaScript, anywhere
within you web page, but it is normally recommended that you should keep it
within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the
text between these tags as a script. A simple syntax of your JavaScript will
appear as follows.
<script ...>
JavaScript code
</script>
The script tag takes two important attributes
 Language − This attribute specifies what scripting language you are
using. Typically, its value will be JavaScript. Although recent versions
of HTML (and XHTML, its successor) have phased out the use of this
attribute.
 Type − this attribute is what is now recommended to indicate the
scripting language in use and its value should be set to
"text/javascript".
Your First JavaScript Script
Let us take a sample example to print out "Hello World". We added an
optional HTML comment that surrounds our JavaScript code. This is to save
our code from a browser that does not support JavaScript. The comment ends
with a "//-->". Here "//" signifies a comment in JavaScript, so we add that to
prevent a browser from reading the end of the HTML comment as a piece of
JavaScript code. Next, we call a function document.write which writes a
string into our HTML document.
This function can be used to write text, HTML, or both. Take a look at
the following code.
<Html>
<Body>
<script language="JavaScript" type="text/JavaScript">
<!--
Document t. write ("Hello World!")
//-->
</script>
</body>
</html>

63
This code will produce the following result
Hello World!
Whitespace and Line Breaks
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript
programs. You can use spaces, tabs, and newlines freely in your program and
you are free to format and indent your programs in a neat and consistent way
that makes the code easy to read and understand.
Semicolons are Optional
Simple statements in JavaScript are generally followed by a semicolon
character, just as they are in C, C++, and Java. JavaScript, however, allows
you to omit this semicolon if each of your statements are placed on a separate
line. For example, the following code could be written without semicolons.
Script language="JavaScript" type="text/JavaScript">
<!--
var1 = 10
var2 = 20
//-->
</script>
But when formatted in a single line as follows, you must use semicolons
<script language="JavaScript" type="text/JavaScript">
<!--
var1 = 10; var2 = 20;
//-->
</script>
Note − It is a good programming practice to use semicolons.
Case Sensitivity
JavaScript is a case-sensitive language. This means that the language
keywords, variables, function names, and any other identifiers must always be
typed with a consistent capitalization of letters.
So the identifiers Time and TIME will convey different meanings in
JavaScript.
NOTE − Care should be taken while writing variable and function names in
JavaScript.
Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus

64
 Any text between a // and the end of a line is treated as a comment and
is ignored by JavaScript.
 Any text between the characters /* and */ is treated as a comment. This
may span multiple lines.
 JavaScript also recognizes the HTML comment opening sequence <!--.
JavaScript treats this as a single-line comment, just as it does the //
comment.
 The HTML comment closing sequence --> is not recognized by
JavaScript so it should be written as //-->.
Example
The following example shows how to use comments in JavaScript.
<script language="JavaScript" type="text/JavaScript">
<!--
// This is a comment. It is similar to comments in C++
/*
* This is a multiline comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>
2.4 Primitives, Operations and Expressions
Primitive data type is either of the following
Basic type is a data type provided by a programming language as a
basic building block. Most languages allow more complicated composite
types to be recursively constructed starting from basic types.
 a built-in type is a data type for which the programming language provides
built-in support.
In most programming languages, all basic data types are built-in. In
addition, many languages also provide a set of composite data types. Opinions
vary as to whether a built-in type that is not basic should be considered
"primitive".
Depending on the language and its implementation, primitive data types
may or may not have a one-to-one correspondence with objects in the
computer's memory. However, one usually expects operations on basic
primitive data types to be the fastest language constructs there are Integer
addition, for example, can be performed as a single machine instruction, and

65
some processors offer specific instructions to process sequences of characters
with a single instruction In particular, the C standard mentions that "a 'plain' int
object has the natural size suggested by the architecture of the execution
environment". This means that int is likely to be 32 bits long on a 32-bit
architecture. Basic primitive types are almost always value types.
Most languages do not allow the behavior or capabilities of primitive
(either built-in or basic) data types to be modified by programs. Exceptions
include Smalltalk, which permits all data types to be extended within a
program, adding to the operations that can be performed on them or even
redefining the built-in operations.
The actual range of primitive data types that is available is dependent
upon the specific programming language that is being used. For example,
in C, strings are a composite but built-in data type, whereas in modern dialects
of BASIC and inJavaScript, they are assimilated to a primitive data type that is
both basic and built-in.
Classic basic primitive types may include:
 Character (character, char);
 Integer (integer, int, short, long, byte) with a variety of precisions;
 Floating-point number (float, double, real, double Precision Fixed-point
number (fixed) with a variety of precisions and a programmer-
selected scale.
 Boolean, logical values true and false.
 Reference (also called a pointer or handle), a small value referring to
another object's address in memory, possibly a much larger one.
More sophisticated types which can be built-in include:
 Tuple in ML, Python
 List in Lisp
 Complex number in Fortran, C (C99), Lisp, Python, Perl 6, D
 Rational number in Lisp, Perl 6
 Associative array in various guises, in Lisp, Perl, Python, Lua, D
 First-class function, closure, continuation in languages that support
functional programming such as Lisp, ML, Perl 6, D and C# 3.0
Specific primitive data types

66
Integer numbers
An integer data type can hold a whole number, but no fraction. Integers
may be either signed (allowing negative values) or unsigned (nonnegative
values only).
Table 2.4 Typical sizes of integers are:

Size Size Unsigned


Names Signed Range
(bytes) (bits) Range

1 byte 8 bits Byte −128 to +127 0 to 255

2 bytes 16 bits Word, short int −32,768 to +32,767 0 to 65,535

Double Word,
long int (win32, −2,147,483,648 to 0 to
4 bytes 32 bits
win64, 32-bit +2,147,483,647 4,294,967,295
[2]
Linux )

long int (C in
64-bit linux[2]), −9,223,372,036,854,77
0 to
long long (C), 5,808 to
8 bytes 64 bits 18,446,744,073
long (Java, the +9,223,372,036,854,77
,709,551,615
signed integer 5,807
variant only[3])

-( ( 2 ^ unlimited ) / 2 )
unlimit unlimit 0 to 2 ^
Bignum to +( ( 2 ^ unlimited )
ed / 8 ed unlimited
/2)

Literals for integers consist of a sequence of digits. Table 2.4 Most


programming languages disallow use of commas for digit grouping,
although Fortran (77, 90, and above, fixed form source but not free form
source) allows embedded spaces, and Perl, Ruby, Java and D allow embedded
underscores. Negation is indicated by a minus sign (−) before the value.
Examples of integer literals are:
 42
 10000
 −233000
Boolean
A boolean type, typically denoted "bool" or "boolean", is typically
a logical type that can be either "true" or "false". Although only one bit is

67
necessary to accommodate the value set "true" and "false", programming
languages typically implement Boolean types as one or more bytes.
Most languages (Java, Pascal and Ada, e.g.) implement Booleans
adhering to the concept of Boolean as a distinct logical type. Languages,
though, may implicitly convert Booleans to numeric types at times to give
extended semantics to Booleans and Boolean expressions or to achieve
backwards compatibility with earlier versions of the language. In C++, e.g.,
Boolean values may be implicitly converted to integers, according to the
mapping false → 0 and true → 1 (for example, would be a valid expression
evaluating to 2). The Boolean type Bool in C++ is considered an integral type
and is a cross between numeric type and a logical type.
Floating-point numbers
A floating-point number represents a limited-precision rational
number that may have a fractional part. These numbers are stored internally in
a format equivalent to scientific notation, typically in binary but sometimes
in decimal. Because floating-point numbers have limited precision, only a
subset of real or rational numbers are exactly representable; other numbers can
be represented only approximately.
Many languages have both a single precision (often called "float") and
a double precision type.
Literals for floating point numbers include a decimal point, and
typically use "e" or "E" to denote scientific notation. Examples of floating-point
literals are:
 20.0005
 99.9
 −5000.12
 6.02e23
Some languages (e.g., Fortran, Python, D) also have a complex number
type comprising two floating-point numbers: a real part and an imaginary part.
Fixed-point numbers
A fixed-point number represents a limited-precision rational number
that may have a fractional part. These numbers are stored internally in a scaled-
integer form, typically in binary but sometimes in decimal. Because fixed-point
numbers have limited precision, only a subset of real or rational numbers are
exactly representable; other numbers can be represented only approximately.
Fixed-point numbers also tend to have a more limited range of values
than floating point, and so the programmer must be careful to avoid overflow in
intermediate calculations as well as the final results.

68
Characters and strings
A character type (typically called "char") may contain a
single letter, digit, punctuation mark, symbol, formatting code,control code, or
some other specialized code (e.g., a byte order mark). In C, char is defined as
the smallest addressable unit of memory. On most systems, this is 8 bits;
several standards, such as POSIX, require it to be this size. Some languages
have two or more character types, for example a single-byte type
for ASCII characters and a multi-byte type for Unicode characters. The term
"character type" is normally used even for types whose values more precisely
represent code units, for example a UTF-16 code unit as in Java and JavaScript.
Characters may be combined into strings. The string data can include numbers
and other numerical symbols but will be treated as text.
Strings are implemented in various ways, depending on the
programming language. The simplest way to implement strings is to create
them as an array of characters, followed by a delimiting character used to signal
the end of the string, usuallyNUL. These are referred to as null-terminated
strings, and are usually found in languages with a low amount of hardware
abstraction, such as C and Assembly. While easy to implement, null terminated
strings have been criticized for causingbuffer overflows. Most high-level
scripting languages, such as Python, Ruby, and many dialects of BASIC, have
no separate character type; strings with a length of one are normally used to
represent single characters. Some languages, such as C++and Java, have the
capability to use null-terminated strings (usually for backwards-compatibility
measures), but additionally provide their own class for string handling
(std::String and Java.Long.String, respectively) in the standard library.
There is also a difference on whether or not strings are mutable
or immutable in a language. Mutable strings may be altered after their creation,
whereas immutable strings maintain a constant size and content. In the latter,
the only way to alter strings are to create new ones. There are both advantages
and disadvantages to each approach: although immutable strings are much less
flexible, they are simpler and completely thread-safe. Some examples of
languages that use mutable strings include C++, Perl, and Ruby, whereas
languages that do not include JavaScript, Lua, and Go. A few languages, such
as Objective-C, provide different types for mutable and immutable strings.
Literals for characters and strings are usually surrounded by quotation
marks: sometimes, single quotes (') are used for characters and double quotes
(") are used for strings.

69
Examples of character literals in C syntax are:
 'A'
 '4'
 '$'
 '\t' (tab character)
Examples of string literals in C syntax are:
"A"
"Hello World"
Numeric data type ranges
Each numeric data type has its maximum and minimum value known as
the range. Attempting to store a number outside the range may lead to
compiler/runtime errors, or to incorrect calculations (due to truncation)
depending on the language being used.
The range of a variable is based on the number of bytes used to save the
value, and an integer data type is usually able to store values (where is
the number of bits that contribute to the value). For other data types
(e.g. floating point values) the range is more complicated and will vary
depending on the method used to store it. There are also some types that do not
use entire bytes, e.g. a boolean that requires a single bit, and represents
a binary value (although in practice a byte is often used, with the remaining 7
bits being redundant). Some programming languages (such as Ada and Pascal)
also allow the opposite direction, that is, the programmer defines the range and
precision needed to solve a given problem and the compiler chooses the most
appropriate integer or floating point type automatically.
JavaScript Expressions and Operators
 Expressions
 Operators
o Arithmetic Operators
o Bitwise Operators
o Logical Operators
o Comparison Operators
o String Operators
o Operator Precedence
Expressions
An expression is any valid set of literals, variables, operators, and
expressions that evaluates to a single value. The value may be a number, a

70
string, or a logical value. Conceptually, there are two types of expressions:
those that assign a value to a variable, and those that simply have a value. For
example, the expression
x=7
is an expression that assigns x the value 7. This expression itself evaluates to 7.
Such expressions use assignment operators. On the other hand, the expression
3+4
simply evaluates to 7; it does not perform an assignment. The operators used in
such expressions are referred to simply as operators.
JavaScript has the following kinds of expressions:
 Arithmetic: evaluates to a number, for example
 String: evaluates to a character string, for example "Fred" or "234"
 Logical: evaluates to true or false
The special keyword null denotes a null value. In contrast, variables
that have not been assigned a value are undefined, and cannot be used without a
run-time error.
Conditional Expressions
A conditional expression can have one of two values based on a
condition. The syntax is
(Condition) ? val1: val2
If condition is true, the expression has the value of val1, Otherwise it
has the value of val2. You can use a conditional expression anywhere you
would use a standard expression.
For example,
Status = (age >= 18) ? "adult" : "minor"
This statement assigns the value "adult" to the variable status if age is
eighteen or greater. Otherwise, it assigns the value "minor" to status.
Assignment Operators (=, +=, -=, *=, /=)
An assignment operator assigns a value to its left operand based on the
value of its right operand. The basic assignment operator is equal (=), which
assigns the value of its right operand to its left operand. That is, x = y assigns
the value of y to x.
The other operators are shorthand for standard arithmetic operations as follows:
 x += y means x = x + y
 x -= y means x = x - y
 x *= y means x = x * y

71
 x /= y means x = x / y
 x %= y means x = x % y
There are additional assignment operators for bitwise operations:
 x <<= y means x = x << y
 x >>= y means x = x >> y
 x >>>= means x = x >>> y
 x &= means x = x & y
 x ^= means x = x ^ y
 x |= means x = x | y
Operation
Live Script has arithmetic, string, and logical operators. There are
both binary and unary operators. A binary operator requires two operands, one
before the operator and one after the operator:
Operand1 operator operand2
For example, 3 + 4 or x * y
A unary operator requires a single operand, either before or after the
operator:
Operator operand
Or
Operand operator
For example x++ or ++x.
Arithmetic Operators
Arithmetic operators take numerical values (either literals or variables)
as their operands and return a single numerical value.
Standard Arithmetic Operators
The standard arthmetic operators are addition (+), subtraction (-), multiplication
(*), and division (/). These operators work in the standard way.
Modulus (%)
The modulus operator is used as follows:
var1 % var2
The modulus operator returns the first operand modulo the second
operand, that is, var1 modulo var2, in the statement above, where var1 and
var2 are variables. The modulo function is the remainder of integrally
dividing var1 by var2. For example, 12 % 5 returns 2.

72
Increment (++)
The increment operator is used as follows:
var++ or ++var
This operator increments (adds one to) its operand and returns a value.
If used postfix, with operator after operand (for example x++), then it returns
the value before incrementing. If used prefix with operator before operand (for
example, ++x), then it returns the value after incrementing.
For example, if x is 3, then the statement
y = x++
Increments x to 4 and sets y to 3.
If x is 3, then the statement
y = ++x
increments x to 4 and sets y to 4.
Decrement (--)
The decrement operator is used as follows:
var-- or --var
This operator decrements (subtracts one from) its operand and returns a
value. If used postfix (for example x--) then it returns the value before
decrementing. If used prefix (for example, --x), then it returns the value after
decrementing.
For example, if x is 3, then the statement
y = x--
Decrements x to 2 and sets y to 3.
If x is 3, then the statement
y = --x
Decrements x to 2 and sets y to 2.
Unary negation (-)
The unary negation operator must precede its operand. It negates its
operand. For example,
x = -x
negates the value of x; that is if x were 3, it would become -3.
Bitwise Operators
Bitwise operators treat their operands as a set of bits (zeros and ones),
rather than as decimal, hexadecimal, or octal numbers. For example, the
decimal number 9 has a binary representation of 101. Bitwise operators

73
perform their operations on such binary representations, but they return
standard JavaScript numerical values.
Bitwise Logical Operators
The bitwise operators are:
 Bitwise AND &. Returns a one if both operands are ones.
 Bitwise OR |. Returns a one if either operand is one.
 Bitwise XOR ^. Returns a one if one but not both operands are one.
The bitwise logical operators work conceptually as follows:
 The operands are converted to 32-bit integers, and expressed a series of
bits (zeros and ones).
 Each bit in the first operand is paired with the corresponding bit in the
second operand: first bit to first bit, second bit to second bit, and so on.
 The operator is applied to each pair of bits, and the result is constructed
bitwise.
Bitwise Shift Operators
The bitwise shift operators are:
 Left Shift (<<)
 Sign-propagating Right Shift (>>)
 Zero-fill Right shift (>>>)
The shift operators take two operands: the first is a quantity to be
shifted, and the second specifies the number of bit positions by which the first
operand is to be shifted. The direction of the shift operation is controlled by the
operator used.
Shift operators convert their operands to 32-bit integers, and return a
result of the same type as the left operator.
Left Shift (<<)
This operator shifts the first operand the specified number of bits to the
left. Excess bits shifted off to the left are discarded. Zero bits are shifted in
from the right.
Example TBD.
Sign-propagating Right Shift (>>)
This operator shifts the first operand the specified number of bits to the
right. Excess bits shifted off to the right are discarded. Copies of the leftmost
bit are shifted in from the left.

74
Example TBD.
Zero-fill right shift (>>>)
This operator shifts the first operand the specified number of bits to the
left. Excess bits shifted off to the right are discarded. Zero bits are shifted in
from the left.
Example TBD.
Logical Operators
Logical operators take logical (Boolean) values as operands. They
return a logical value. Logical values are true and false.
And (&&)
Usage: expr1 && expr2
The logical "and" operator returns true if both logical
expressions expr1 and expr2 are true. Otherwise, it returns false.
Or (||)
Usage: expr1 || expr2
The logical "or" operator returns true if either logical
expression expr1 or expr2 is true. If both expr1 and expr2 are false, then it
returns false.
Not (!)
Usage: !expr
The logical "not" operator is a unary operator that negates its operand
expression expr. That is, if expr is true, it returns false, and if expr is false, then
it returns true.
Short-Circuit Evaluation
As logical expressions are evaluated left to right, they are tested for
possible "short circuit" evaluation using the following rule:
 False && anything is short-circuit evaluated to false.
 True || anything is short-circuit evaluated to true.
The rules of logic guarantee that these evaluations will always be
correct. Note that the anything part of the above expressions is not evaluated, so
any side effects of doing so do not take effect.
Comparison Operators (= =, >, >=, <, <=, !=)
A comparison operator compares its operands and returns a logical
value based on whether the comparison is true or not. The operands may be
numerical or string values. When used on string values, the comparisons are
based on the standard lexicographical ordering.

75
The operators are:
 Equal (= =): returns true if the operands are equal.
 Not equal (!=): returns true if the operands are not equal.
 Greater than (>): returns true if left operand is greater than right
operand. Example: x > y returns true if x is greater than y.
 Greater than or equal to (>=): returns true if left operand is greater than
or equal to right operand. Example: x >= y returns true if x is greater
than or equal to y.
 Less than (<): returns true if left operand is less than right operand.
Example: x < y returns true if x is less than y.
 Less than or equal to (<=): returns true if left operand is less than or
equal to right operand. Example: x <= y returns true if x is less than or
equal to y.
String Operators
In addition to the comparison operators, which may be used on string
values, the concatenation operator (+) concatenates two string values together,
returning another string that is the union of the two operand strings. For
example,
"My” + "string"
Returns the string
"my string"
The shorthand assignment operator += can also be used to concatenate
strings. For example, if the variable mystring is a string that has the value
"alpha", then the expression
mystring += "bet"
evaluates to "alphabet" and assigns this value to mystring.
Operator Precedence
The precedence of operators determines the order they are applied when
evaluating an expression. You can override operator precedence by using
parentheses.
The precedence of operators, from lowest to highest is as follows:
comma ,
assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=
conditional ?:
logical-or ||
logical-and &&

76
bitwise-or |
bitwise-xor ^
bitwise-and &
equality ==!=
relational < <= > >=
shift << >> >>>
addition/subtraction + -
multiply/divide * / %
Negation/increment! ~ - ++ --
call, member () [] .
2.5 Screen Output & Keyboard Input
 The JavaScript model for the HTML document is the Document object
 The model for the browser display window is the Window object
o The Window object has two properties, document and window,
which refer to the document and window objects, respectively
 The Document object has a method, write, which dynamically creates
content
o The parameter is a string, often catenated from parts, some of
which are variables
e.g., document.write("Answer: " + result + "<br />");
 The Window object has three methods for creating dialog boxes, alert,
confirm, and prompt
1. alert("Hej! \n");
 Parameter is plain text, not HTML
 Opens a dialog box which displays the parameter string
and an OK button
2. confirm("Do you want to continue?");
 Opens a dialog box and displays the parameter and two
buttons, OK and Cancel
3. prompt("What is your name?", "");
 Opens a dialog box and displays its string parameter,
along with a text box and two buttons, OK and Cancel
 The second parameter is for a default response if the user
presses OK without typing a response in the text box
(waits for OK)

77
Find solutions for a quadratic equation
<! DOCTYPE html>
<! -- roots.html
A document for roots.js
-->
<html Lang = "en">
<Head>
<Title> roots.html </title>
<Meta charset = "utf-8" />
</head>
<Body>
<script type = "text/JavaScript” src = "roots.js" >
</script>
</body>
</html>
// roots.js
// Compute the real roots of a given quadratic
// equation. If the roots are imaginary, this script
// displays NaN, because that is what results from
// taking the square root of a negative number
// Get the coefficients of the equation from the user
var a = prompt("Find the solution for ax^2 + bx +c \n What is the value of 'a'?
\n", "");
var b = prompt("What is the value of 'b'? \n", "");
var c = prompt("What is the value of 'c'? \n", "");
// Compute the square root and denominator of the result
var root_part = Math.sqrt(b * b - 4.0 * a * c);
var denom = 2.0 * a;
// Compute and display the two roots
var root1 = (-b + root_part) / denom;
var root2 = (-b - root_part) / denom;
document.write("The first root is: ", root1, "<br />");
document.write("The second root is: ", root2, "<br />");

78
2.6 Control statements
A program executes from top to bottom except when we use control
statements, we can control the order of execution of the program, based on
logic and values. In Java, control statements can be divided into the following
three categories:
 Selection Statements
 Iteration Statements
 Jump Statements
Selection Statements
Selection statements allow you to control the flow of program execution
on the basis of the outcome of an expression or state of a variable known during
runtime.
Selection statements can be divided into the following categories:
 The if and if-else statements
 The if-else statements
 The if-else-if statements
 The switch statements
If statements
The first contained statement (that can be a block) of an if statement
only executes when the specified condition is true. If the condition is false and
there is not else keyword then the first contained statement will be skipped and
execution continues with the rest of the program. The condition is an
expression that returns a boolean value.
Example
Package com.deepak.main;
Import java.util.Scanner;
Public class IfDemo
{
Public static void main (String [] args) {
Int age;
Scanner input Device = new Scanner (System. in);
System.out.print ("Please enter Age: ");
Age = inputDevice.nextInt ();
If (age > 18)
System.out.println ("above 18 ");

79
}
}
Output

The if-else statements


In if-else statements, if the specified condition in the if statement is
false, then the statemet after the else keyword (that can be a block) will
execute.
Example
package com.deepak.main;
Import java.util.Scanner;
Public class IfElseDemo
{
Public static void main (String [] args )
{
Int age;
Scanner inputDevice = new Scanner (System.in);
System.out.print ( "Please enter Age: " );
Age = inputDevice.nextInt ();
If (age >= 18)
System.out.println (“above 18 " );
Else
System.out.println (“below 18" );
}
}
Output

80
if-else-if statements
This statement following the else keyword can be another if or if-else
statement.
That would looks like this:
if(condition)
statements;
else if (condition)
statements;
else if(condition)
statement;
else
statements;
Whenever the condition is true, the associated statement will be
executed and the remaining conditions will be bypassed. If none of the
conditions are true then the else block will execute.
Example
Package com.deepak.main;
Import java.util.Scanner;
Public class IfElseIfDemo
{ . Public static void main (String [] args)
{
Int age;
Scanner inputDevice = new Scanner (System. in );
System.out.print (“Please enter Age: " );
Age = inputDevice.nextInt ();
If ( age >= 18 && age <=35 )
System.out.println ( "between 18-35 " );
. Else if(age >35 && age <=60)
System.out.println ("between 36-60");
Else
System.out.println ( "not matched" );
}
}

81
Output

The Switch Statements


The switch statement is a multi-way branch statement. The switch
statement of Java is another selection statement that defines multiple paths of
execution of a program. It provides a better alternative than a large series of if-
else-if statements.
Example
Package com.deepak.main;
Import java.util.Scanner;
Public class Switch Demo
{
Public static void main( String[] args )
{
Int age;
Scanner inputDevice = new Scanner (System. in );
System.out.print ( "Please enter Age: " );
Age = inputDevice.nextInt ();
Switch (age )
{
Case 18:
System.out.println ( "age 18" );
Break;
Case 19:
System.out.println ( "age 19" );
Break;
Default:
System.out.println ( "not matched" );
Break;

82
}
}
}
Output

An expression must be of a type of byte, short, int or char. Each of the


values specified in the case statement must be of a type compatible with the
expression. Duplicate case values are not allowed. The break statement is used
inside the switch to terminate a statement sequence. The break statement is
optional in the switch statement.
Iteration Statements
repeating the same code fragment several times until a specified
condition is satisfied is called iteration. Iteration statements execute the same
set of instructions until a termination condition is met.
Java provides the following loop for iteration statements:
 The while loop
 The for loop
 The do-while loop
 The for each loop
The while loop
It continually executes a statement (that is usually be a block) while a
condition is true. The condition must return a Boolean value.
Example
Package com.deepak.main;
Public class While Demo
{
Public static void main( String[] args )
{
Int i = 0;

83
While ( i < 5 )
{
System.out.println( "Value :: " + i );
i++;
}
}
}
Output

The do-while loop


The only difference between a while and a do-while loop is that do-
while evaluates its expression at the bottom of the loop instead of the top. The
do-while loop executes at least one time then it will check the expression prior
to the next iteration.
Example
1. package com.deepak.main;
2.
3. public class DoWhileDemo
4. {
5. public static void main( String[] args )
6. {
7. int i = 0;
8. do
9. {
10. System.out.println( "value :: " + i );
11. i++;
12. }
13. while ( i < 5);

84
14. }
15. }
Output

The for loop


A for loop executes a statement (that is usually a block) as long as the
boolean condition evaluates to true. A for loop is a combination of the three
elements initialization statement, Boolean expression and increment or
decrement statement.
Syntax:
for(<initialization>;<condition>;<increment or decrement statement>){
<block of code>
}
The initialization block executes first before the loop starts. It is used to
initialize the loop variable.
The condition statement evaluates every time prior to when the
statement (that is usually be a block) executes, if the condition is true then only
the statement (that is usually a block) will execute.
The increment or decrement statement executes every time after the
statement (that is usually a block).
Example
1. package com.deepak.main;
2.
3. public class While Demo
4. {
5. public static void main( String[] args )
6. {
7. int i = 0;
8. while ( i < 5 )

85
9. {
10. System.out.println( "Value :: " + i );
11. i++;
12. }
13. }
14. }
Output

The For each loop


This was introduced in Java 5. This loop is basically used to traverse the
array or collection elements.
Example
1. package com.deepak.main;
2.
3. public class ForEachDemo
4. {
5. public static void main( String[] args )
6. {
7. int[] i =
8. { 1, 2, 3, 4, 5 };
9. for ( int j : i )
10. {
11. System.out.println( "value :: " + j );
12. }
13. }
14. }

86
Output

Jump Statements
Jump statements are used to unconditionally transfer the program
control to another part of the program.
Java provides the following jump statements:
 break statement
 continue statement
 return statement
Break Statement
The break statement immediately quits the current iteration and goes to
the first statement following the loop. Another form of break is used in the
switch statement.
The break statement has the following two forms:
 Labeled Break Statement
 Unlabeled Break Statement
Unlabeled Break Statement: This is used to jump program control out of
the specific loop on the specific condition.
Example
1. package com.deepak.main;
2. public class UnLabeledBreakDemo
3. {
4. public static void main( String[] args )
5. {
6. for ( int var = 0; var < 5; var++ )
7. {
8. System.out.println( "Var is : " + var );
9. if ( var == 3 )
10. break;

87
11. }
12. }
13. }
Output

Labeled Break Statement: This is used for when we want to jump the
program control out of nested loops or multiple loops.
Example
1. package com.deepak.main;
2.
3. public class LabeledBreakDemo
4. {
5. public static void main( String[] args )
6. {
7. Outer: for ( int var1 = 0; var1 < 5; var1++ )
8. {
9. for ( int var2 = 1; var2 < 5; var2++ )
10. {
11. System.out.println( "var1:" + var1 + ", var2:" + var2 );
12. if ( var1 == 3 )
13. break Outer;
14. }
15. }
16. }
17. }

88
Output

Continue Statement
the continue statement is used when you want to continue running the
loop with the next iteration and want to skip the rest of the statements of the
body for the current iteration.
The continue statement has the following two forms:
 Labeled Continue Statement
 Unlabeled Continue Statement
Unlabeled Continue Statement: This statement skips the current iteration of
the innermost for, while and do-while loop.
Example
1. package com.deepak.main;
2.
3. public class UnlabeledContinueDemo
4. {
5. public static void main( String[] args )
6. {
7. for ( int var1 = 0; var1 < 4; var1++ )
8. {
9. for ( int var2 = 0; var2 < 4; var2++ )
10. {
11. if ( var2 == 2 )
12. continue;

89
13. System.out.println( "var1:" + var1 + ", var2:" + var2 );
14. }
15. }
16. }
17. }
Example

Labeled Continue Statement: This statement skips the current iteration of the
loop with the specified label.
Example
1. package com.deepak.main;
2.
3. public class LabeledContinueDemo
4. {
5. public static void main( String[] args )
6. {
7. Outer: for ( int var1 = 0; var1 < 5; var1++ )
8. {
9. for ( int var2 = 0; var2 < 5; var2++ )
10. {
11. if ( var2 == 2 )
12. continue Outer;
13. System.out.println( "var1:" + var1 + ", var2:" + var2 );
14. }
15. }

90
16. }
17. }
Output

Return Statement
The return statement is used to immediately quit the current method and
return to the calling method. It is mandatory to use a return statement for non-
void methods to return a value.
Example
1. package com.deepak.main;
2.
3. public class ReturnDemo
4. {
5. public static void main( String[] args )
6. {
7. ReturnDemo returnDemo = new ReturnDemo();
8. System.out.println( "No : " + returnDemo.returnCall() );
9. }
10.
11. int returnCall()
12. {
13. return 5;
14. }
15. }

91
Output

2.7 Object Creation Modification, Arrays


JavaScript arrays are used to store multiple values in a single variable.
Displaying Arrays
In this tutorial we will use a script to display arrays inside a <p> element with
id="demo":
Example
<p id="demo"></p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
The first line (in the script) creates an array named cars.
The second line "finds" the element with id="demo", and "displays" the array
in the "innerHTML" of it.
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:
Var car1 = "Saab";
Var car2 = "Volvo";
Var car3 = "BMW";
However, what if you want to loop through the cars and find a specific one?
And what if you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the
values by referring to an index number.
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.

92
Syntax:
Var array-name = [item1, item2,,,,];
Example:
Var cars = ["Saab", "Volvo", "BMW"];

Using the JavaScript Keyword new


The following example also creates an Array, and assigns values to it:
Example
var cars = new Array("Saab", "Volvo", "BMW");
Access the Elements of an Array
You refer to an array element by referring to the index number.
This statement accesses the value of the first element in cars:
Var name = cars [0];
This statement modifies the first element in cars:
Cars [0] = "Opel";
You Can Have Different Objects in One Array
JavaScript variables can be objects. Arrays are special kinds of objects.
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can
have arrays in an Array:
My Array [0] = Date. Now;
My Array [1] = my Function;
My Array [2] = my Cars;
Arrays are Objects
Arrays are a special type of objects. The typeof operator in JavaScript returns
"object" for arrays.
But, JavaScript arrays are best described as arrays.
Arrays use numbers to access its "elements". In this example, person[0] returns
John:
Array:
var person = ["John", "Doe", 46];
Array Properties and Methods
The real strength of JavaScript arrays are the built-in array properties and
methods:

93
Example
Var x = cars. Length; // The length property returns the number of
elements in cars
var y = cars.sort(); // The sort() method sort cars in alphabetical order
Array methods are covered in the next chapter.
The length Property
The length property of an array returns the length of an array (the number of
array elements).
Example
Var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits. Length; // the length of fruits is 4
Adding Array Elements
The easiest way to add a new element to an array is using the push method:
Example
Var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits. Push("Lemon"); // adds a new element (Lemon) to fruits
Looping Array Elements
The best way to loop through an array, is using a "for" loop:
Example
Var index;
var fruits = ["Banana", "Orange", "Apple", "Mango"];
for (index = 0; index < fruits.length; index++) {
text += fruits[index];
}
When to Use Arrays? When to use Objects?
 JavaScript does not support associative arrays.
 You should use objects when you want the element names to be strings
(text).
 You should use arrays when you want the element names to
be numbers.

Avoid new Array ()


There is no need to use the JavaScript's built-in array constructor new Array().
Use [] instead.
These two different statements both create a new empty array named points:

94
var points = new Array(); // Bad
var points = []; // Good
These two different statements both create a new array containing 6 numbers:
var points = new Array(40, 100, 1, 5, 25, 10) // Bad
var points = [40, 100, 1, 5, 25, 10]; // Good
2.8 Function construction
The function statement is not the only way to define a new function;
you can define your function dynamically using Function() constructor along
with the new operator.
Note − Constructor is a terminology from Object Oriented Programming. You
may not feel comfortable for the first time, which is OK.
Syntax
Following is the syntax to create a function using Function
() constructor along with the new operator.
<script type="text/javascript">
<!--
var variable name = new Function(Arg1, Arg2..., "Function Body");
//-->
</script>
The Function () constructor expects any number of string arguments.
The last argument is the body of the function – it can contain arbitrary
JavaScript statements, separated from each other by semicolons.
Notice that the Function () constructor is not passed any argument that
specifies a name for the function it creates. The unnamed functions created
with the Function() constructor are called anonymous functions.
Example
Try the following example.
<Html>
<Head>
<script type="text/javascript">
<!--
Var func = new Function ("x", "y", "return x*y;");
Function second Function (){
Var result;
Result = func (10, 20);

95
Document. Write (result);
}
//-->
</script>
</head>
<Body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()" value="Call
Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
2.9 Pattern matching using regular expressions
Regular Expressions patterns
The patterns used in RegExp can be very simple, or very complicated,
depending on what you're trying to accomplish. To match a simple string like
"Hello World!" is no harder then actually writing the string, but if you want to
match an e-mail address or html tag, you might end up with a very complicated
pattern that will use most of the syntax presented in the table below.
Pattern and then Description:
Escaping
\ Escapes special characters to literal and literal
characters to special.

E.g.: /\(s\)/ matches '(s)' while /(\s)/ matches any


whitespace and captures the match.
Quantifiers
{n}, {n,}, {n,m}, *,+, ? Quantifiers match the preceding sub pattern a
certain number of times. The sub pattern can be a
single character, an escape sequence, a pattern
enclosed by parentheses or a character set.

{n} matches exactly n times.


{n,} matches n or more times.
{n,m} matches n to m times.

96
* is short for {0,}. Matches zero or more times.
+ is short for {1,}. Matches one or more times.
? is short for {0,1}. Matches zero or one time.

E.g.: /o{1,3}/ matches 'oo' in "tooth" and 'o' in


"nose".
Pattern delimiters
(pattern),(?:pattern) Matches entire contained pattern.

(Pattern) captures match.


(?:pattern) doesn't capture match

E.g.: /(d).\1/ matches and captures 'dad' in


"abcdadef" while /(?:.d){2}/ matches but doesn't
capture 'cdad'.

Note: (?: pattern) is a JavaScript 1.5 feature.


Lookaheads
(?=pattern),(?!pattern) Look ahead matches only if the preceding sub
expression is followed by the pattern, but the
pattern is not part of the match. The sub
expression is the part of the regular expression
which will be matched.

(? =pattern) matches only if there is a


following pattern in input.
(?!Pattern) matches only if there is not a
following pattern in input.
E.g.: /Win (? =98)/ matches 'Win' only if 'Win' is
followed by '98'.
Note: Look ahead is a JavaScript1.5 feature.
Alternation
| Alternation matches content on either side of the
alternation character.
E.g.: / (a|b)a/ matches 'aa' in "dseaas" and 'ba' in
"acbab".

97
Character sets
[characters], Matches any of the contained characters. A range
[^characters] of characters may be defined by using a hyphen.
[Characters] matches any of the
contained characters.
[^characters] negates the character set and
matches all but the contained characters
E.g.: / [abcd]/ matches any of the characters 'a',
'b', 'c',’d’ and may be abbreviated to / [a-d]/.
Ranges must be in ascending order, otherwise
they will throw an error. (E.g: /[d-a]/ will throw
an error.)
/[^0-9]/ matches all characters but digits.
Note: Most special characters are automatically
escaped to their literal meaning in character sets.
Special characters
^, $, ., ? and all the Special characters are characters that match
highlighted characters something else than what they appear as.
above in the table. ^ matches beginning of input (or new line
with m flag).
$ matches end of input (or end of line
with m flag).
. Matches any character except a newline.
? directly following a quantifier makes the
quantifier non-greedy (makes it match minimum
instead of maximum of the interval defined).

E.g.: / (.)*? / matches nothing or '' in all strings.

Note: Non-greedy matches are not supported in


older browsers such as Netscape Navigator 4 or
Microsoft Internet Explorer 5.0.
Literal characters
All characters except those Mapped directly to the corresponding character.
with special meaning.
E.g.: /a/ matches 'a' in "Any ancestor".

98
Back references
\n Back references are references to the same thing
as a previously captured match. n is a positive
nonzero integer telling the browser which
captured match to reference to.

/(\S)\1(\1)+/g matches all occurrences of three


equal non-whitespace characters following each
other.
/< (\S+).*> (.*)<\/\1>/ matches any tag.
E.g.: /< (\S+).*> (.*)<\/\1>/ matches '<div
id="me">text</div>' in "text<div
id=\"me\">text</div>text".
Character Escapes
\f, \r, \n, \t, \v,\0, [\b], \s, \S \f matches form-feed.
, \w,\W, \d, \D, \b, \B,\cX, \r matches carriage return.
\xhh, \uhhhh \n matches linefeed.
\t matches horizontal tab.
\v matches vertical tab.
\0 matches NUL character.
[\b] matches backspace.
\s matches whitespace (short
for [\f\n\r\t\v\u00A0\u2028\u2029]).
\S matches anything but a whitespace (short
for [^\f\n\r\t\v\u00A0\u2028\u2029]).
\w matches any alphanumerical character (word
characters) including underscore (short for [a-zA-
Z0-9_]).
\W matches any non-word characters (short
for [^a-zA-Z0-9_]).
\d matches any digit (short for [0-9]).
\D matches any non-digit (short for [^0-9]).
\b matches a word boundary (the position between
a word and a space).
\B matches a non-word boundary (short for [^\b]).
\cX matches a control character. E.g: \cm matches
control-M.
\xhh matches the character with two characters of
hexadecimal code hh.
\uhhhh 0matches the Unicode character with four
characters of hexadecimal code hhhh.

99
NOTES
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………

100
NOTES
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………

101
UNIT – III

Dynamic Documents using JavaScript


In This Chapter
 Java Script Execution Environment
 Document Object Model (DOM)
 Element Access in Java Script
 Events and Events Handling
 Handling Events from Body Elements
 Button Elements
 Textbox and Password Elements
 DOM Tree traversal and Modification
 Positioning Elements
 Moving Elements
 Elements Visibility
 Changing colors and fonts
 Dynamic Content
 Stacking Elements
 Locating the Mouse Cursor, Reacting to a Mouse Click
 Dragging and Dropping Elements
3.1 JavaScript Execution Environment
What is JavaScript?
JavaScript is a cross-platform, object-oriented scripting language. It is a
small and lightweight language. Inside a host environment, JavaScript can be
connected to the objects of its environment to provide programmatic control
over them.
JavaScript contains a standard library of objects, such as Array, Date,
and Math, and a core set of language elements such as operators, control
structures, and statements. Core JavaScript can be extended for a variety of
purposes by supplementing it with additional objects; for example:
 Client-side JavaScript extends the core language by supplying objects
to control a browser and its Document Object Model (DOM). For
example, client-side extensions allow an application to place elements
on an HTML form and respond to user events such as mouse clicks,
form input, and page navigation.

102
 Server-side JavaScript extends the core language by supplying objects
relevant to running JavaScript on a server. For example, server-side
extensions allow an application to communicate with a database,
provide continuity of information from one invocation to another of the
application, or perform file manipulations on a server.
Script execution timeline
There are various things that can cause a script to start executing.
Reading a <script> tag is one such thing. An event firing is another, which
schedules a function to be called before the next page redraw. That is yet
another way in which a script can start running.It is important to understand
that even though events can fire at any time, no two scripts in a single
document ever run at the same moment. If a script is already running, event
handlers and pieces of code scheduled in other ways have to wait for their turn.
This is the reason why a document will freeze when a script runs for a long
time. The browser cannot react to clicks and other events inside the document
because it can’t run event handlers until the current script finishes running.
Some programming environments do allow multiple threads of execution to run
at the same time. Doing multiple things at the same time can be used to make a
program faster. But when you have multiple actors touching the same parts of
the system at the same time, thinking about a program becomes at least an order
of magnitude harder.
The fact that JavaScript programs do only one thing at a time makes our
lives easier. For cases where you really do want to dosome time-consuming
thing in the background without freezing the page, browsers provide something
calledweb workers. A worker is an isolated JavaScript environment that runs
alongside the main program for a document and can communicate with it only
by sending and receiving messages. Assume we have the following code in a
file called code/squareworker.js:addEventListener("message",function(event){
postMessage(event.data * event.data);}); that squaring a number is a heavy,
long-running computation that we want to perform in a background thread.
This code spawns a worker, sends it a few messages, and outputs the responses.
Var squareWorker = new Worker("code/squareworker.js");
squareWorker.addEventListener("message", function(event) {
console.log("The worker responded:", event.data);
});
squareWorker.postMessage(10);
squareWorker.postMessage(24);

103
The postMessage function sends a message, which will cause
a "message"event to fire in the receiver. The script that created the worker
sends and receives messages through the Worker object, whereas the worker
talks to the script that created it by sending and listening directly on its global
scope—which is a new global scope, not shared with the original script.
JavaScript and Java
JavaScript and Java are similar in some ways but fundamentally
different in some others. The JavaScript language resembles Java but does not
have Java's static typing and strong type checking. JavaScript follows most
Java expression syntax, naming conventions and basic control-flow constructs
which was the reason why it was renamed from LiveScript to JavaScript.
In contrast to Java's compile-time system of classes built by
declarations, JavaScript supports a runtime system based on a small number of
data types representing numeric, Boolean, and string values. JavaScript has a
prototype-based object model instead of the more common class-based object
model. The prototype-based model provides dynamic inheritance; that is, what
is inherited can vary for individual objects. JavaScript also supports functions
without any special declarative requirements. Functions can be properties of
objects, executing as loosely typed methods.
JavaScript is a very free-form language compared to Java. You do not
have to declare all variables, classes, and methods. You do not have to be
concerned with whether methods are public, private, or protected, and you do
not have to implement interfaces. Variables, parameters, and function return
types are not explicitly typed.
Java is a class-based programming language designed for fast execution
and type safety. Type safety means, for instance, that you can't cast a Java
integer into an object reference or access private memory by corrupting Java
bytecodes. Java's class-based model means that programs consist exclusively of
classes and their methods. Java's class inheritance and strong typing generally
require tightly coupled object hierarchies. These requirements make Java
programming more complex than JavaScript programming.
In contrast, JavaScript descends in spirit from a line of smaller,
dynamically typed languages such as HyperTalk and dBASE. These scripting
languages offer programming tools to a much wider audience because of their
easier syntax, specialized built-in functionality, and minimal requirements for
object creation.

104
JavaScript compared to Java
JavaScript Java
Object-oriented. No distinction Class-based. Objects are divided into
between types of objects. Inheritance is classes and instances with all
through the prototype mechanism, and inheritance through the class
properties and methods can be added hierarchy. Classes and instances
to any object dynamically. cannot have properties or methods
added dynamically.
Variable data types are not declared Variable data types must be declared
(dynamic typing). (static typing).
Cannot automatically write to hard Can automatically write to hard disk.
disk.
The JavaScript Window object represents the window in which the
browser displays documents. he Window object provides the largest enclosing
referencing environment for scripts. All global variables are properties of
Window. Implicitly defined Window properties:.document a reference to the
Document object that the window displaysframes an array of references to the
frames of the document Every Document object has:forms an array of
references to the forms of the documentEach Form object has an elements
array, which has references to the form’s elements Document also has anchors,
links, images,style
3.2 The Document Object Model
When you open a web page in your browser, the browser retrieves the
page’s HTML text and parses it,. The browser builds up a model of the
document’s structure and then uses this model to draw the page on the screen.
This representation of the document is one of the toys that a JavaScript
program has available in its sandbox. You can read from the model and also
change it. It acts as a live data structure: when it is modified, the page on the
screen is updated to reflect the changes.
Document structure
You can imagine an HTML document as a nested set of boxes. Tags
such as<body> and </body> enclose other tags, which in turn contain other
tags or text. Here’s the example
Edit & run code by clicking it
<!doctype html>
<Html>

105
<Head>
<Title>My home page</title>
</head>
<Body>
<h1>my home page</h1>
<p>Hello, I am Marijn and this is my home page.</p>
<p>I also wrote a book! Read it
<a href="http://eloquentjavascript.net">here</a>.</p>
</body>
</html>
This page has the following structure:
The data structure the browser uses to represent the document follows
this shape. For each box, there is an object, which we can interact with to find
out things such as what HTML tag it represents and which boxes and text it
contains. This representation is called the Document Object Model or DOM for
short.
The global variable document gives us access to these objects. Its
document Element property refers to the object representing the <html> tag. It
also provides the properties head and body, which hold the objects for those
elements.
The Document Object Model (DOM) is a programming interface for
HTML, XML and SVG documents. It provides a structured representation of
the document (a tree) and it defines a way that the structure can be accessed
from programs so that they can change the document structure, style and
content. The DOM provides a representation of the document as a structured
group of nodes and objects that have properties and methods. Nodes can also
have event handlers attached to them, and once that event is triggered the event
handlers get executed. Essentially, it connects web pages to scripts or
programming languages. Though often accessed using JavaScript, the DOM
itself is not a part of the JavaScript language, and it can be accessed by other
languages, though this is much less common.
"The Document Object Model (DOM) is a platform and language-
neutral interface that allows programs and scripts to dynamically access and
update the content, structure, and style of a document."
The DOM standard is separated into 3 different parts:
 Core DOM - standard model for all document types
 XML DOM - standard model for XML documents

106
 HTML DOM - standard model for HTML documents
The HTML DOM is a standard object model and programming interface for
HTML. It defines:
 The HTML elements as objects
 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements
In other words: The HTML DOM is a standard for how to get,
change, add, or delete HTML elements.
 DOM 0 is supported by all JavaScript-enabled browsers (no written
specification)
 DOM 1 was released in 1998
 DOM 2 is the latest approved standard
 Nearly completely supported by NS7
 IE6’s support is lacking some important things
 The DOM is an abstract model that defines the interface between
 HTML documents and application programs—an API
 A language that supports the DOM must have a binding to the
 In the JavaScript binding, HTML elements are represented as objects
and element attributes are represented as properties e.g.,<input type =
"text" name = "address">
 would be represented as an object with two properties, type and
name, with the values "text" and "address
The DOM tree is completely comprised of JavaScript objects. Some of
the fundamental and most commonly-used ones are listed in Table3.1
Table 3.1 Commonly used JavaScript DOM types
DOM Definition
object

Returns the document object for the page. Represents the root
document node of the DOM tree, and actions on it will affect the entirety of
the page.
element Represents an instance of most structures and sub-structures in
the DOM tree. For example, a text block can be an element, and
so can the entire body section of an HTML document.

107
nodeList A nodeList is equivalent to an array, but it is an array specific to
storing elements. You can access items in a nodeList through
common syntax like myList[n], where n is an integer.

There are a number of JavaScript methods specified by the DOM which


allow you to access its structure. Some of the fundamental and most
commonly-used ones are listed in Table 3.2.
Table 3.2 Commonly used JavaScript DOM methods
DOM method Parent class(es) Definition
element get document, Returns the element uniquely
Element By Id (id) element identified by its id identifier.
Node List get document, Returns a nodeList of any elements
Elements By Tag element that have a given tag (such
Name (name) as p or div), specified by name.
element create element Creates an element with the type
Element(type) specified by type (such as por div)
void append Child element, node Appends the node specified
(node) by node onto the receiving node or
element.
string style element Returns the style rules associated
with an element, in string form.
You can also use this to set the
style rules, by calling something
like div.style.margin = “10px”;
string innerHTML element Returns the HTML that contains
the current element and all the
content within it. You can also use
this to set the innerHTML of an
element, by using something
likeelement.innerHTML =
“<p>test</p>”;
void setAttribute(na element Adds (or changes) an attribute of
me,value) the receiving element, such as
its id or align attribute.
string getAttribute( element Returns the value of the element
name) attribute specified by name.

108
3.3 Element Access in JavaScript
JavaScript provides the ability for getting the value of an element on a
webpage as well as dynamically changing the content within an element.
Focuses on:
 Getting the value of an element
 Changing the content within an element
Getting the value of an element
To get the value of an element, the getElementById method of
the document object is used. For this method to get the value of an element,
that element has to have an id given to it through the idattribute.
Example:
<script type="text/JavaScript">
Function getText()
{
//access the element with the id 'textOne' and get its value
//assign this value to the variable theText var theText =
document.getElementById('textOne').value; alert
("The text in the textbox is” + theText);
}
</script>
<input type="text" id="textOne" />
<input type="button" value="Get text" onclick="getText()" />
Changing the content within an element
To change the content within an element, use
the innerHTML property. Using this property, you could replace the text in
paragraphs, headings and other elements based on several things such as a
value the user enters in a textbox. For this property to change the content
within an element, that element has to have an 'id' given to it through
the id attribute.
Example:
<script type="text/JavaScript">
Function changeTheText()
{
//change the innerHTML property of the element whose id is 'text' to 'So is
HTML!' document.getElementById('text').innerHTML = 'So is HTML!';

109
}
</script>
<p id="text">JavaScript is cool!</p>
<input type='button' onclick='changeTheText()' value='Change the text' />
There are several ways to do it
Example (a document with just one form and one widget):
<form action = "">
<input type = "button"name = "pushMe">
</form>
1. DOM address
document.forms[0].element[0]
Problem: document changes
2. Element names – requires the element and all of its ancestors
(except body) to have name attributes
Example:
<form name = "myForm"action = "">
<input type = "button"name = "pushMe">
</form>
document.myForm.pushMe
Problem: XHTML 1.1 spec doesn’t allow the
name attribute on form elements
3. getElementById Method (defined in DOM 1)
Example:
<form action = "">
<input type = "button"id = "pushMe">
</form>
document.getElementById("pushMe")
Checkboxes and radio button have an implicit array, which has their name
<form id = "topGroup"><input type = "checkbox"name =
"toppings"value = "olives" />
...
<input type ="checkbox“ name=“toppings” value ="tomatoes" />
</form>
...

110
var numChecked = 0;
Var dom = document.getElementById("topGroup");
for index = 0; index < dom.toppings.length; index++
if dom.toppings[index].checked] numChecked++;
3.4 Events and Event Handling
Introduction to Events
Events are the beating heart of any JavaScript application. On
this page I give an overview of what event handling is, what its problems
are and how to write proper cross-browser scripts. I will also provide
pages with the gory details of event handling.
Without events there are no scripts. Take a look at any web page with
JavaScript in it: in nearly all cases there will be an event that triggers the script.
The reason is very simple. JavaScript is meant to add interactivity to your
pages: the user does something and the page reacts.
Therefore JavaScript needs a way of detecting user actions so that it
knows when to react. It also needs to know which functions to execute,
functions that do something that you, the web developer, have judged likely to
increase the appeal of your pages. These pages describe the best way to write
such scripts. It isn’t easy, but it is very satisfying work.
When the user does something an event takes place. There are also
some events that aren’t directly caused by the user: the load event that fires
when a page has been loaded, for instance.
JavaScript can detect some of these events. From Netscape 2 onwards
it has been possible to attach an event handler to certain HTML elements —
mostly links and form fields in the early days. The event handler waits until a
certain event, for instance a click on a link, takes place. When it happens
it handles the event by executing some JavaScript you have defined.
When the user takes action he causes an event. When your script
makes the page react to this event, interactivity is born.
Events and accessibility
Before we delve deeper into explaining how to control and call events, I
just want to emphasize accessibility. While it’s normally a broad term for most
people, I use it here to convey that what you want to do through the usage of
events really should work when JavaScript is disabled or for other reasons
blocked in the web browser.
Some people do turn off JavaScript in their web browsers, but more
commonly proxy servers, firewalls and overzealous antivirus programs stop

111
JavaScript from behaving as expected. Don’t let this discourage you; my aim is
to guide you through creating events that have an accessible fallback in case of
JavaScript not being available.
In general, never apply events to HTML elements that don’t already
have a built-in behavior for that certain event. You should only apply onclick
events to elements like a, which already have a fallback behavior for click
events (eg browsing to the location specified in the link, or submitting a form).
Controlling events
Let’s start out with a simple example of an event, and how you can react
to it. For the sake of simplicity, I will be using the addEvent solution referred to
above, to avoid delving into the intricacies of cross-browser workarounds in
each example.
Our first example is the onload event, which belongs to the window
object. Generally, any events that affect the browser window (like onload,
onresize and onscroll) are available through the window object.
The onload event takes place when everything in the web page has
completely loaded. This includes the HTML code itself as well as external
dependencies such as images, CSS files and JavaScript files. When all of them
have finished loading, window.onload gets called, and you can trigger web
page functionality to occur. The following very simple example makes an alert
message appear when the page has loaded:
History of event handling
Imagine an interface where the only way to find out whether a key on
the keyboard is being pressed is to read the current state of that key. To be able
to react to keypresses, you would have to constantly read the key’s state so that
you’d catch it before it’s released again. It would be dangerous to perform other
time-intensive computations since you might miss a keypress.
That is how such input was handled on primitive machines. A step up
would be for the hardware or operating system to notice the keypress and put it
in a queue. A program can then periodically check the queue for new events
and react to what it finds there.
Of course, it has to remember to look at the queue, and to do it often,
because any time between the key being pressed and the program noticing the
event will cause the software to feel unresponsive. This approach is
called polling. Most programmers avoid it whenever possible.
A better mechanism is for the underlying system to give our code a
chance to react to events as they occur.

112
The best scripts are those that react to something the user does.
Therefore, when Netscape released its Version 2 browser which supported
JavaScript, it also supported events.
An event is a notification that something specific has occurred, either
with the browser or an action of the browser user An event handler is a script
that is implicitly executed in response to the appearance of an event The
process of connecting an event handler to an event is called registration
Don’t use document.write in an event handler, because the output may
go on top of the display
The same attribute can appear in several different tags e.g., The
onclick attribute can be in <a> and <input>A text element gets focus in three
ways: When the user puts the mouse cursor over it and presses the left button
When the user tabs to the element
By executing the focus method
Accessing the event
When you’ve registered your event handler you start writing the actual
script. Usually you want to access the event itself, so you can read out
information about the event.
Table 3.3 and Table 3.4 Explain the Event and tag attribute To access
the event so that you can read out its properties, always start your event
handling function thus:
doSomething(e) {
if (!e) var e = window.event
// e refers to the event
}

113
Table3.3 Event Accessing

Table3.4 Attribute Description

3.5 Handling Events from Body Elements


Introduction
Now you are comfortable with using CSS for styling and layout, and
have taken your first stumbling steps with understanding variables, functions,
methods, etc. in JavaScript, it is time to start using that knowledge to provide

114
your site visitors with interactivity and dynamic behavior (such as dragging and
dropping, animation, etc). Controlling events with JavaScript allows you to step
into the role as Doctor Frankenstein and really give life to your creations!
But enough about the joys of JavaScript—this Web Standards
Curriculum article will get practical, telling you what events are and how to
make use of them on your pages.
Bear in mind that you can download the code example for this article and try it
out for yourself.
The evolution of events
In the early days of Java Scripting, we used event handlers directly
within the HTML element, like this:
<a href="http://www.opera.com/" onclick="alert ('Hello')">Say hello</a>
The problem with this approach is that it resulted in event handlers
spread throughout the code, no central control and missing out on web
browsers' caching features when it comes to external JavaScript file includes.
The next step in event evolution was to apply events from within a JavaScript
block, for example:
<script type="text/JavaScript">
document.getElementById("my-link").onclick = waveToAudience;
Function waveToAudience()
{
alert ("Waving like I've never waved before!");
}
</script>
<a id="my-link" href="http://www.opera.com/">My link</a>
Note the clean HTML in the last example. This is generally what’s
referred to as unobtrusive JavaScript. The benefit of this, besides JavaScript
caching and code control, is code separation: you have all your content in one
location and your interaction code in another. This also allows for a more
accessible approach where the link will work perfectly fine with JavaScript
disabled; it is also something that will please search engines.
Handling Events from Button Elements
Plain Buttons – use the onclick property
Radio buttons
If the handler is registered in the markup, the particular button that was
clicked can be sent to the handler as a parameter

115
e.g., if planeChoice is the name of the handler and the value of a button is
172, use
onclick = ″planeChoice(172)″
This is another way of choosing the clicked button
SHOW radio_click.html & display
If the handler is registered by assigning it to a property of the
JavaScript objects associated with the HTML elements. As in:
var dom = document.getElementById(″myForm″)
dom.elements[0].onclick = planeChoice;
This registration must follow both the handler function and the
XHTML form
If this is done for a radio button group, each element of the array must be
assigned
In this case, the checked property of a radio button object is used to
determine whether a button is clicked
If the name of the buttons is planeButton
var dom = document.getElementById(″myForm″);
for (var index = 0;
index < dom.planeButton.length; index++) {
if (dom.planeButton[index].checked) {
plane = dom.planeButton[index].value;
break; }}
The disadvantage of specifying handlers by assigning them to event properties
is that there is no way to use parameters
The advantages of specifying handlers by assigning them to event
properties are:
1. It is good to keep HTML and JavaScript separate
2. The handler could be changed during use
Handling Events from Textbox and Password
Elements
The Focus Event
Can be used to detect illicit changes to a text box by blurring the
element every time the element acquires focus
SHOW nochange.html

116
Checking Form Input
A good use of JavaScript, because it finds errors in form input before it
is sent to the server for processing
So, it saves both:
1. Server time, and
2. Internet time
Things that must be done:
1. Detect the error and produce an alert message
2. Put the element in focus (the focus function)
3. Select the element (the select function)
The focus function puts the element in focus, which puts the cursor in
the element document.getElementById("phone").focus();
The select function highlights the text in the element
To keep the form active after the event handler is finished, the handler
must return false
Problems:
1. With IE6, focus and select only work if the handler is registered by
assigning it to the element event property
2. With NS7, select works, but focus does not
Example – comparing passwords
The form just has two password input boxes to get the passwords and
Reset and Submit buttons
The event handler is triggered by the Submit button
Handler actions:
1. If no password has been typed in the first box, focus on that box and return
false
2. If the two passwords are not the same, focus and select the first box and
return false if they are the same, return true
--> SHOW pswd_chk.html
Another Example – Checking the format of a name and phone number The
event handler will be triggered by the change event of the text boxes for the
name and phone number
If an error is found in either, an alert message is produced and both
Focus and select are called on the text box element
SHOW validator.html

117
3.6 DOM Tree Traversal:
Every node's DOM object has the following properties: name(s)
description firstChild, lastChild start/end of this node's list of children child
Nodes array of all this node's children nextSibling, previous Sibling
neighboring nodes with the same parent Fig 3.1.
Parent Node the element that contains this node complete list of DOM
node properties browser incompatibility information (IE6 sucks)
DOM tree traversal example 1

DOM tree traversal example 2

Fig 3.1 Modifying the DOM tree

118
3.7 Element Positioning with CSS
For DHTML content developers, the most important feature of CSS is
the ability to use ordinary CSS style attributes to specify the visibility, size, and
precise position of individual elements of a document. In order to do DHTML
programming, it is important to understand how these style attributes work.
They are summarized in Table 3.4 and documented in more detail in the
sections that follow.
Table.3.4 .The Key to DHTML: The position Attribute

The CSS position attribute specifies the type of positioning applied to


an element. The four possible values for this attribute are:
Static
This is the default value and specifies that the element is positioned
according to the normal flow of document content (for most Western
languages, this is left to right and top to bottom.) Statically positioned elements
are not DHTML elements and cannot be positioned with the top, left, and other
attributes. To use DHTML positioning techniques with a document element,
you must first set its position attribute to one of the other three values.
Absolute
This value allows you to specify the position of an element relative to
its containing element. Absolutely positioned elements are positioned
independently of all other elements and are not part of the flow of statically
positioned elements. An absolutely positioned element is positioned either
relative to the <body> of the document or, if it is nested within another
absolutely positioned element, relative to that element. This is the most
commonly used positioning type for DHTML.

119
Fixed
This value allows you to specify an element's position with respect to
the browser window. Elements with fixed positioning do not scroll with the rest
of the document and thus can be used to achieve frame-like effects. Like
absolutely positioned elements, fixed-position elements are independent of all
others and are not part of the document flow. Fixed positioning is a CSS2
feature and is not supported by fourth-generation browsers. (It is supported in
Netscape 6 and IE 5 for the Macintosh, but it is not supported by IE 5 or IE 6
for Windows).
Relative
When the position attribute is set to relative, an element is laid out
according to the normal flow, and its position is then adjusted relative to its
position in the normal flow. The space allocated for the element in the normal
document flow remains allocated for it, and the elements on either side of it do
not close up to fill in that space, nor are they "pushed away" from the new
position of the element. Relative positioning can be useful for some static
graphic design purposes, but it is not commonly used for DHTML effects.
Once you have set the position attribute of an element to something
other than static, you can specify the position of that element with some
combination of the left, top, right, and bottom attributes. The most common
positioning technique is to specify the left and top attributes, which specify the
distance from the left edge of the containing element (usually the document
itself ) to the left edge of the element, and the distance from the top edge of the
container to the top edge of the element. For example, to place an element 100
pixels from the left and 100 pixels from the top of the document, you can
specify CSS styles in a style attribute as follows:
<div style="position: absolute; left: 100px; top: 100px;">
The containing element relative to which a dynamic element is
positioned is not necessarily the same as the containing element within which
the element is defined in the document source. Since dynamic elements are not
part of normal element flow, their positions are not specified relative to the
static container element within which they are defined. Most dynamic elements
are positioned relative to the document (the <body> tag) itself. The exception is
dynamic elements that are defined within other dynamic elements. In this case,
the nested dynamic element is positioned relative to its nearest dynamic
ancestor.
Although it is most common to specify the position of the upper-left
corner of an element with left and top, you can also use right and bottom to
specify the position of the bottom and right edges of an element relative to the

120
bottom and right edges of the containing element. For example, to position an
element so that its bottom-right corner is at the bottom-right of the document
(assuming it is not nested within another dynamic element), use the following
styles:
position: absolute; right: 0px; bottom: 0px;
To position an element so that its top edge is 10 pixels from the top of
the window and its right edge is 10 pixels from the right of the window, you
can use these styles:
position: fixed; right: 10px; top: 10px;
Note that the right and bottom attributes are newer additions to the CSS
standard and are not supported by fourth-generation browsers, as top and left
are.
In addition to the position of elements, CSS allows you to specify their
size. This is most commonly done by providing values for the width and height
style attributes. For example, the following HTML creates an absolutely
positioned element with no content. Its width, height, and background-color
attributes make it appear as a small blue square:
<div style="position: absolute; left: 10px; right: 10px;
width: 10px; height: 10px; background-color: blue">
</div>
Another way to specify the width of an element is to specify a value for
both the left and right attributes. Similarly, you can specify the height of an
element by specifying both top and bottom. If you specify a value for left, right,
and width, however, the width attribute overrides the right attribute; if the
height of an element is over-constrained, height takes priority over bottom.
Bear in mind that it is not necessary to specify the size of every
dynamic element. Some elements, such as images, have an intrinsic size.
Furthermore, for dynamic elements that contain text or other flowed content, it
is often sufficient to specify the desired width of the element and allow the
height to be determined automatically by the layout of the element's content.
In the previous positioning examples, values for the position and size
attributes were specified with the suffix "px". This stands for pixels. The CSS
standard allows measurements to be done in a number of other units, including
inches ("in"), centimeters ("cm"), points ("pt"), and ems ("em" -- a measure of
the line height for the current font). Pixel units are most commonly used with
DHTML programming. Note that the CSS standard requires a unit to be
specified. Some browsers may assume pixels if you omit the unit specification,
but you should not rely on this behavior.

121
Instead of specifying absolute positions and sizes using the units shown
above, CSS also allows you to specify the position and size of an element as a
percentage of the size of the containing element. For example, the following
HTML creates an empty element with a black border that is half as wide and
half as high as the containing element (or the browser window) and centered
within that element:
<div style="position: absolute; left: 25%; top: 25%; width: 50%; height:
50%;
border: 2px solid black">
</div>
Element size and position details
It is important to understand some details about how the left , right,
width, top, bottom, and height attributes work. First, width and height specify
the size of an element's content area only; they do not include any additional
space required for the element's padding, border, or margins. To determine the
full onscreen size of an element with a border, you must add the left and right
padding and left and right border widths to the element width, and you must
add the top and bottom padding and top and bottom border widths to the
element's height.
Since width and height specify the element content area only, you might
think that left and top (and right and bottom) would be measured relative to the
content area of the containing element. In fact, the CSS standard specifies that
these values are measured relative to the outside edge of the containing
element's padding (which is the same as the inside edge of the element's
border).
Let's consider an example to make this clearer. Suppose you've created
a dynamically positioned container element that has 10 pixels of padding all the
way around its content area and a 5 pixel border all the way around the
padding. Now suppose you dynamically position a child element inside this
container. If you set the left attribute of the child to "0 px", you'll discover that
the child is positioned with its left edge right up against the inner edge of the
container's border. With this setting, the child overlaps the container's padding,
which presumably was supposed to remain empty (since that is the purpose of
padding). If you want to position the child element in the upper left corner of
the container's content area, you should set both the left and top attributes to
"10px". Figure 3.2 helps to clarify this.

122
Figure3.2: Dynamically positioned container and child elements with some
CSS attributes
Now that you understand that width and height specify the size of an
element's content area only and that the left, top, right, and bottom attributes are
measured relative to the containing element's padding, there is one more detail
you must be aware of: Internet Explorer Versions 4 through 5.5 for Windows
(but not IE 5 for the Mac) implement the width and height attributes incorrectly
and include an element's border and padding (but not its margins). For example,
if you set the width of an element to 100 pixels and place a 10-pixel margin and
a 5-pixel border on the left and right, the content area of the element ends up
being only 70 pixels wide in these buggy versions of Internet Explorer.
In IE 6, the CSS position and size attributes work correctly when the
browser is in standards mode and incorrectly (but compatibly with earlier
versions) when the browser is in compatibility mode. Standards mode, and
hence correct implementation of the CSS "box model," is triggered by the
presence of a <!DOCTYPE> tag at the start of the document, declaring that the
document adheres to the HTML 4.0 (or later) standard or some version of the
XHTML standards. For example, any of the following three HTML document
type declarations cause IE 6 to display documents in standards mode:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Strict//EN">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"
Netscape 6 and the Mozilla browser handle the width and height
attributes correctly. But these browsers also have standards and compatibility
modes, just as IE does. The absence of a <!DOCTYPE> declaration puts the
Netscape browser in quirks mode, in which it mimics certain (relatively minor)
nonstandard layout behaviors of Netscape 4. The presence of <!DOCTYPE>

123
causes the browser to break compatibility with Netscape 4 and correctly
implement the standards.
The Third Dimension: z-index
We've seen that the left, top, right, and bottom attributes can be used to
specify the X and Y coordinates of an element within the two-dimensional
plane of the containing element. The z-index attribute defines a kind of third
dimension: it allows you to specify the stacking order of elements and indicate
which of two or more overlapping elements is drawn on top of the others. The
z-index attribute is an integer. The default value is zero, but you may specify
positive or negative values (although fourth-generation browsers may not
support negative z-index values). When two or more elements overlap, they are
drawn in order from lowest to highest z-index; the element with the highest z-
index appears on top of all the others. If overlapping elements have the same z-
index, they are drawn in the order in which they appear in the document, so the
last overlapping element appears on top.
Note that z-index stacking applies only to sibling elements (i.e.,
elements that are children of the same container). If two elements that are not
siblings overlap, setting their individual z-index attributes does not allow you to
specify which one is on top. Instead, you must specify the z-index attribute for
the two sibling containers of the two overlapping elements.
Nonpositioned elements are always laid out in a way that prevents
overlaps, so the z-index attribute does not apply to them. Nevertheless, they
have a default z-index of zero, which means that positioned elements with a
positive z-index appear on top of the normal document flow, and positioned
elements with a negative z-index appear beneath the normal document flow.
Note, finally, that some browsers do not honor the z-index attribute
when it is applied to <iframe> tags, and you may find that inline frames float
on top of other elements, regardless of the specified stacking order. You may
have the same problem with other "windowed" elements such as <select> drop-
down menus. Fourth-generation browsers may display all form-control
elements on top of absolutely positioned elements, regardless of z-index
settings.
3.8 Moving HTML elements around
Beyond simple style enhancements to HTML documents lies re-
organising how the existing document parts are laid in the browser window.
Changing the layout of an HTML document comes down to manipulating the
CSS-P style attributes of absolutely and relatively positioned elements.

124
The important style properties for this class of effect are:
Position
Left, top, width and height
Clip and overflow
Z-index
The position style property is absolutely critical. If it is not set to
'relative' or 'absolute', then the element that the style applies to will not be
movable at all. Setting the position property 'frees' the element for movement;
otherwise it is 'embedded' in the rest of the document.
The idea of 2.5-D animation pervades this kind of Dynamic HTML. For
complex movement effects, the z-order must be carefully planned for all the
movable elements in the page. However, for simple effects this is not usually
necessary.
A further restriction on moving HTML around is that of coordinate
systems: there must be some way to tell the difference between 'here' and
'there'. You need to decide at the start whether to fit in with the browser's layout
of the document and use percentage measures, or whether to go straight to
specific pixel-by-pixel measurements. If the user can resize the window
displaying the document, or if the document must work for browsers running at
many different screen resolutions, then choose percentage measures. If you
want to do highly accurate movement, then you should create a non-resizable
browser window using window.open() and perform all your movement within
that window on a pixel-by-pixel basis.
Types of Movement
Movement of HTML elements can be expressed in several different
ways. In the following examples, balloon.gif looks like this:
Of course, movement is not restricted to images—any kind of content
can be used, from simple text to complex chunks of HTML markup.
Automated movement
User input isn't always required before HTML elements can move
around. Via JavaScript, motion can be had automatically. This first example
illustrates:
<HTML><HEAD>
<STYLE>
#zephyr { position: absolute; left: 0; top: 0; }
</STYLE>
<SCRIPT>

125
Function drift()
{
var z = document.all.zephyr.style;
if ( z.pixelTop < 200 && z.pixelLeft == 0 ) z.pixelTop +=5;
else if ( z.pixelLeft < 200 && z.pixelTop == 200 ) z.pixelLeft +=5;
else if ( z.pixelTop <= 200 && z.pixelTop > 0 ) z.pixelTop -=5;
else if ( z.pixelLeft <= 200 && z.pixelLeft > 0) z.pixelLeft -= 5;
}
</SCRIPT></HEAD>
<BODY ONLOAD="setInterval('drift()',1)">
<DIV ID="zephyr">
<IMG SRC="balloon.gif"><BR>
Out, out and about!
</DIV>
</BODY></HTML>
When viewed in Internet Explorer 4.0, this example displays the balloon
moving in a square with diagonally opposite corners at pixel coordinates (0,0)
and (200,200). There are several points to note here:
Redrawing the absolutely positioned element takes time. The
setInterval() delay is one millisecond; if the computer could perform at that
pace, the balloon would travel around the square about 7 times a second, which
it clearly does not. The script must finish ('let go') before the HTML element is
redrawn - if you replace the setInterval() timing mechanism with a while() or
for() loop inside the drift() function, it won't work, because JavaScript will
always be in charge.
Note the use of style properties that report pixel values as integers, not
strings. Recall that '20px' is a valid positional value, but that format is not as
easy to work with as a plain number.
To make the example work in Netscape Navigator 4.0, replace the main
function with this alternative:
function drift()
{
var z = document.layers[0];
if ( z.top < 200 && z.left == 0 ) z.top +=5;
else if ( z.left < 200 && z.top == 200 ) z.left +=5;

126
else if ( z.top <= 200 && z.top > 0 ) z.top -=5;
else if ( z.left <= 200 && z.left > 0) z.left -= 5;
}
This example shows very typical differences between the two browsers.
One of the detection techniques described in Chapter 2 could be used to make
both browsers workable from the one HTML document.
This next very similar example shows how z-order can be used to plan
overlapping animated areas:
<HTML><HEAD>
<STYLE>
#zephyr { position: absolute; left: 0; top: 0; z-index: 1; background-color:
yellow;}
#sirocco { position: absolute; left: 150; top: 150; z-index: 2; }
</STYLE>
<SCRIPT>
function drift()
{
var z = document.all.zephyr.style;
if ( z.pixelLeft == 0 && z.pixelTop == 0 )
z.zIndex = ( z.zIndex == 1 ) ? 3 : 1;
if ( z.pixelTop < 200 && z.pixelLeft == 0 ) z.pixelTop +=5;
else if ( z.pixelLeft < 200 && z.pixelTop == 200 ) z.pixelLeft +=5;
else if ( z.pixelTop <= 200 && z.pixelTop > 0 ) z.pixelTop -=5;
else if ( z.pixelLeft <= 200 && z.pixelLeft > 0) z.pixelLeft -= 5;
z = document.all.sirocco.style;
if ( z.pixelTop < 250 && z.pixelLeft == 150 ) z.pixelTop +=5;
else if ( z.pixelLeft < 250 && z.pixelTop == 250 ) z.pixelLeft +=5;
else if ( z.pixelTop <= 250 && z.pixelTop > 150 ) z.pixelTop -=5;
else if ( z.pixelLeft <= 250 && z.pixelLeft > 150) z.pixelLeft -= 5;
}
</SCRIPT></HEAD>
<BODY ONLOAD="setInterval('drift()',1)">
<IMG ID="zephyr" SRC="balloon.gif"></IMG>
<DIV ID="sirocco"><IMG SRC="balloon.gif"><BR>In, in with a
spin!</DIV>

127
</BODY></HTML>
Non-obvious in the first balloon example was the transparent nature of
the balloon image. 'Black' and 'transparent' are the only colors in that example,
not 'black' and 'white'. In this second example, the original image now has a z-
order that switches with each pass around the square, and a solid background
color. The result is that on odd-numbered passes around the square, the first
image can be seen 'through' the second image, but on even-numbered
occasions, the first image blocks out the second image due to its solid
background color.
User Drag-Drop
Rather than rely on the browser, sometimes the users want to move an
HTML element around on the page themselves. This is more likely to be the
case if the Web page provides puzzles or games. There is an important
distinction between dragging an item from outside the browser onto a browser
window (such as a file icon), and just moving an element around inside the
window it belongs to. Only the latter case is discussed here, since the former
leads into the complexities of operating systems.
For the latter case, the script writer needs to provide the magic—there is
no direct drag-and-drop support in the browser for moving positioned HTML
elements. This can be a bit confusing to understand, so an analogy may help.
Suppose the user is at a picnic, and sees a biscuit they want on the grass. Their
hand reaches for the biscuit, but it moves. No matter how hard they try to grab
the biscuit, it moves away. Eventually the picnickers organize to box the biscuit
in, revealing thousands of bored ants underneath engaged in psychological
warfare against the human race. The ants are moving the biscuit in response to
the user's hand movements.
Back in the browser it works almost the same, except the scriptwriter
acts for the ants. When the user moves the mouse over the item to be dragged,
the item moves in the mouse direction because JavaScript code underneath
detected the mouse movement and moves the HTML item accordingly. The
steps are:
'Prime' the item for dragging with an appropriate handler
Catch all onMouseMove events and update the item's position
'Defuse' the item for dragging with an appropriate handler
In other words, like this (for Internet Explorer 4.0):
<HTML><HEAD>
<STYLE> #zephyr { position: absolute; left: 0; top: 0;} </STYLE>
<SCRIPT>

128
Var primed = false;
Var new_x = 0;
Var new_y = 0;
Function set_drag() { window.primed = !window.primed; }
function handle_move()
{
if ( window.primed == true)
{
window.new_x = window.event.x;
window.new_y = window.event.y;
setTimeout("drag_it()",1);
}
}
Function drag_it()
{
with ( window.document.all.zephyr.style )
{
pixelLeft = window.new_x - pixelWidth/2;
pixelTop = window.new_y - pixelHeight/2;
}
}
</SCRIPT></HEAD>
<BODY ONMOUSEMOVE="handle_move()">
<IMG ID="zephyr" ONCLICK="set_drag()" SRC="balloon.gif"></IMG>
</BODY></HTML>
This example lets you position the balloon anywhere you wish on the
page, using the mouse. This is very specific to Internet Explorer 4.0.
There are three functions in this example. set_drag() is just a switch to
turn dragging on and off; in this case the onClick handler is chosen, so the user
must press and release the mouse button before dragging starts, and again on
finishing. handle_move() picks up all move events from the window and
updates the image. It uses a separate function drag_it() in a timer, not because
of the limitation that JavaScript must 'let go' before the image's position
changes, but because it gives the user time to move the mouse away from the

129
dragged item. Try collapsing drag_it()'s statements into handle_move() and see
how the dragged item 'sticks' to the mouse pointer in a frustrating way.
3.9 Element Display and Visibility
There are two CSS attributes you can use to affect the visibility of a
document element: visibility and display. The visibility attribute is simple:
when the attribute is set to the value hidden, the element is not shown; when it
is set to the value visible, the element is shown. The display attribute is more
general and is used to specify the type of display an item receives. It specifies
whether an element is a block element, an inline element, a list item, and so on.
When display is set to none, however, the affected element is not displayed, or
even laid out, at all.
The difference between the visibility and display style attributes has to
do with their effect on elements that are not dynamically positioned. For an
element that appears in the normal layout flow (with the position attribute set to
static or relative), setting visibility to none makes the element invisible but
reserves space for it in the document layout. Such an element can be repeatedly
hidden and shown without changing the document layout. If an element's
display attribute is set to none, however, no space is allocated for it in the
document layout; elements on either side of it close up as if it were not there.
(visibility and display have equivalent effects when used with absolute- or
fixed-position elements, since these elements are never part of the document
layout anyway.) You'll typically use the visibility attribute when you are
working with dynamically positioned elements. The display attribute is useful
when creating things like expanding and collapsing outlines.
Note that it doesn't make much sense to use visibility or display to make
an element invisible unless you are going to use JavaScript to dynamically set
these attributes and make the element visible at some point![66] You'll see how
you can do this later in the chapter.
There is an exception: if you are creating a document that depends on
CSS, you can warn users of browsers that do not support CSS with code like
this:
Partial Visibility: overflow and clip
The visibility attribute allows you to completely hide a document
element. The overflow and clip attributes allow you to display only part of an
element. The overflow attribute specifies what happens when the content of an
element exceeds the size specified (with the width and height style attributes,
for example) for the element. The allowed values and their meanings for this
attribute are as follows:

130
Visible
Content may overflow and be drawn outside of the element's box if
necessary. This is the default.
Hidden
Content that overflows is clipped and hidden so that no content is ever
drawn outside the region defined by the size and positioning attributes.
Scroll
The element's box has permanent horizontal and vertical scrollbars. If
the content exceeds the size of the box, the scrollbars allow the user to scroll to
view the extra content. This value is honored only when the document is
displayed on a computer screen; when the document is printed on paper, for
example, scrollbars obviously do not make sense.
Auto
Scrollbars are displayed only when content exceeds the element's size,
rather than being permanently displayed.
While the overflow property allows you to specify what happens when
an element's content is bigger than the element's box, the clip property allows
you to specify exactly which portion of an element should be displayed,
whether or not the element overflows. This attribute is especially useful for
scripted DHTML effects in which an element is progressively displayed or
uncovered.
The value of the clip property specifies the clipping region for the
element. In CSS2 clipping regions are rectangular, but the syntax of the clip
attribute leaves open the possibility that future versions of the standard will
support clipping shapes other than rectangles. The syntax of the clip attribute is:
Rect (top right bottom left)
The top, right, bottom, and left values specify the boundaries of the
clipping rectangle relative to the upper-left corner of the element's box.[67] For
example, to display only a 100 x 100-pixel portion of an element, you can give
that element this style attribute:
As the CSS2 specification was originally written, these four values
specified the offset of the edges of the clipping region from each of the
corresponding edges of the element's box. All major browser implementations
got it wrong, however, and interpreted the right and bottom values as offsets
from the left and top edges. Because the implementations consistently disagree
with the specification, the specification is being modified to match the
implementations.

131
Style="clip: rect(0px 100px 100px 0px)"
Note that the four values within the parentheses are length values and
must include a unit specification, such as "px" for pixels. Percentages are not
allowed. Values may be negative to specify that the clipping region extends
beyond the box specified for the element. You may also use the keyword auto
for any of the four values to specify that that edge of the clipping region is the
same as the corresponding edge of the element's box. For example, you can
display just the leftmost 100 pixels of an element with this style attribute:
Style="clip: rect(auto 100px auto auto)"
Note that there are no commas between the values, and the edges of the
clipping region are specified in clockwise order from the top edge.
CSS Positioning Example
Example 18-2 is a nontrivial example using CSS style sheets and CSS
positioning attributes. When this HTML document is displayed in a CSS-
compliant browser, it creates the visual effect of "subwindows" within the
browser window. Figure 3.3 shows the effect created by the code in Example 3.
Although the listing contains no JavaScript code, it is a useful demonstration of
the powerful effects that can be achieved with CSS in general and the CSS
positioning attributes in particular.

Figure 3.3: Windows created with CSS


Example 3. Displaying windows with CSS
<Head>
<style type="text/css">

132
/**
* This is a CSS style sheet that defines three style rules that we use
* in the body of the document to create a "window" visual effect.
* The rules use positioning attributes to set the overall size of the window
* And the position of its components. Changing the size of the window
* requires careful changes to positioning attributes in all three rules.
**/
div.window { /* Specifies size and border of the window */
Position: absolute; /* The position is specified elsewhere */
Width: 300px; height: 200px; /* Window size, not including borders */
Border: outset gray 3px; /* Note 3D "outset" border effect */
}
div.titlebar {/* Specifies position, size, and style of the titlebar */
Position: absolute; /* It's a positioned element */
Top: 0px; height: 18px; /* Titlebar is 18px + padding and borders */
Width: 290px; /* 290 + 5px padding on left and right = 300 */
Background-color: ActiveCaption; /* Use system titlebar color */
Border-bottom: groove black 2px; /* Titlebar has border on bottom only */
Padding: 3px 5px 2px 5px; /* Values clockwise: top, right, bottom, left */
Font: caption; /* Use system font for titlebar */
}
div.content {/* Specifies size, position and scrolling for window content */
Position: absolute; /* It's a positioned element */
Top: 25px; /* 18px title+2px border+3px+2px padding */
Height: 165px; /* 200px total - 25px titlebar - 10px padding */
Width: 290px; /* 300px width - 10px of padding */
Padding: 5px; /* Allow space on all four sides */
Overflow: auto; /* Give us scrollbars if we need them */
Background-color: #ffffff; /* White background by default */
}
</style>
</head>
<Body>
<! -- Here is how we define a window: a "window" div with a titlebar and -->

133
<! -- Content div nested between them. Note how position is specified with -->
<! -- A style attribute that augments the styles from the style sheet. -->
<div class="window" style="left: 10px; top: 10px; z-index: 10;">
<div class="titlebar">Test Window</div>
<div class="content">
1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>0<br> <! -- Lots of lines
to -->
1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>0<br> <! -- demonstrate
scrolling -->
</div>
</div>
<! -- Here's another window with different position, color, and font weight -->
<div class="window" style="left: 170px; top: 140px; z-index: 20;">
<div class="titlebar">Another Window</div>
<div class="content" style="background-color:#d0d0d0; font-weight:bold;">
This is another window. Its <tt>z-index</tt> puts it on top of the other one.
</div>
</div>
</body>
The major shortcoming of this example is that the style sheet specifies a
fixed size for all windows. Because the titlebar and content portions of the
window must be precisely positioned within the overall window, changing the
size of a window requires changing the value of various positioning attributes
in all three rules defined by the style sheet. This is difficult to do in a static
HTML document, but it would not be so difficult if we could use a script to set
all of the necessary attributes.
3.10 Changing colors and fonts
How to change font colors using JavaScript and getElementById()
Do you want to change font colors of div, span and table elements using
JavaScript? Then here is the code that you have been looking for.
The easiest way to do it is by using the JavaScript function
getElementById(), which allows you to access HTML tags via their ID tags.
For instance, if you give a span tag the ID span1, here is how you could access
it via getElementById and change the span tags font style color to red:
document.getElementById (span1).style.color = '#FF0000';

134
Of course you could also build your own function to shorten this whole
process, as is done in the example below:
<html>
<head>
<title>Changing the bg properties of a div</title>
<script language="javascript" type="text/javascript">
function changeFontColor(newFontColor, elementId)
{
document.getElementById(elementId).style.color = newFontColor;
}
</script>
</head>
<body>
<div id="id1">Click on the buttons below to set this DIV's font color!</div>
<br>
<input style="padding-right:5px;" type="button"
onclick="changeFontColor('#FF0000', 'id1');" value="Red">
<input style="padding-right:5px;" type="button"
onclick="changeFontColor('#FF6622', 'id1');" value="Orange">
<input style="padding-right:5px;" type="button"
onclick="changeFontColor('#AAA', 'id1');" value="Grey">
<input style="padding-right:5px;" type="button"
onclick="changeFontColor('#000', 'id1');" value="Black">
</body>
</html>
3.11 Dynamic content
When we refer to dynamic content that you can write in JavaScript, that
means that the web browser can do more than just "read and display", "read and
display"... as it reads in JavaScript code among your HTML, it can make
decisions based upon the way the code is set up, test against some built in
functions, and then write different HTML code according to its programmed
instructions. It may even be programmed to do something randomly different
every time the page loads.
It makes your web pages a bit more "intelligent" than just sitting there
looking pretty!
We can use JavaScript to write any other kind of HTML content using
the format:
document.write('xxxxxxxx xxxxxxxxxx');
document.write('xxxx xxxxxxx xxxxxxx xxxxx');

135
document.write('xx xx xxxxxxxxxxxx xx');
Each line of this code writes a chunk of HTML, that is everything inside of the
single quote characters. This series of JavaScript statements:
document.write('<h1>Wide World of Cheese</h1>')
document.write('<b><i>Not everyone in this world likes cheese');
document.write('as much as I!<i></b><br> -- Colby Jack (1903)');
will produce the exact same display as this chunk of HTML:
<h1>Wide World of Cheese</h1>
<b><i>Not everyone in this world likes cheese
as much as I!<i></b><br> -- Colby Jack (1903)
Now if this was all there was to JavaScript, we would not even be trying
to teach it to you! JavaScript provides other types of information that you can
display that is not available via HTML. There are built in functions that can
provide the current date and time, information about the user's web browser,
and more as we will soon see. But even more than this, we can set up logical
statements to test, so that we can do things like:
If today is Tuesday or Wednesday and the time is after 12:00 PM then
display this custom message morning greeting; but if it is before 12:00 PM,
then display this different message for the afternoon. But if it is Friday, at any
time, let's display a different type of message no matter what time of day it is.
Any other day or time, just display a standard "Have a nice day" message.
JavaScript code gives us some flexibility to create dynamic content that
can behave and display differently to the viewer.
The first thing we will do is to write a series of JavaScript statements
that will create the footers of all of our documents-- but unlike the ones to date
that we have written by hand, this same block of HTML/JavaScript can be cut
and pasted into every document but will also dynamically print (with examples
for this page shown in parentheses):
a. The title of the web page, from the text in the <TITLE>..</TITLE> tags
(27b. JavaScript- Dynamic Content)
b. An e-mail link that by default will insert the web page title as the
subject line (email test with this page title as subject)
c. The date that the document was most recently modified, if valid
(05/21/2004 18:54:29)
d. The actual URL of the file
(http://wwwacs.gantep.edu.tr/docs/tut/tut27b.html)

136
Not all web servers provide accurate document modification dates, item
(c), and typically when you are testing documents on your desktop computer,
you will not be able to get this information and it would print some erroneous
date like January 1900. We will show you how to test for these conditions. Item
(d) is extremely useful because if we were to move our web pages to different
web servers or re-arrange our site, the URL would be updated automatically.
The template for our "standard" web page footer for the Volcano Web
project looks like the code below. We'll present it first section by section with
some explanations. It's not critical that you understand exactly how it works,
since when you incorporate it into your working pages; it will be simply a cut
and paste operation.
Table3.5
JavaScript Footers
HTML code explanation
<!-- start of Volcano Web standard footers Marks the beginning of the footer
--> area, with proper JavaScript tags
<SCRIPT LANGUAGE="JavaScript">
<!-- hide scripts from old browsers
document.write('<p><hr> Horizontal rule, begin text font
<FONT FACE="helvetica,arial" size=-1> size and main web site title
<i>Volcano Web:</i> <B>');
document.write(document.title + Write the current document title
'</B><BR>');
document.write('created by Lorrie Lava, '); Credits for page with an e-mail
document.write('<A link that automatically inserts the
HREF="mailto:[email protected]?subje page title into the subject line.
ct='
+ document.title + '">');
document.write('[email protected]</A>
<br>');
document.write('Volcanic Studies, More static content.
<A HREF="http://www.bigu.edu/">');
document.write('Big
University</A><p>');</tt></font>
// append a modification date only if This looks tricky. We have set up
// server provides a valid date a conditional test on the value
if (Date.parse(document.lastModified) > that is returned by
document.lastModified, and if it

137
0) { is valid (a non zero return from
document.write('<B>last modified: </B>' a functionwe use
called Date.parse, we write the
+ document.lastModified + '<BR>');
modification date. If we do not
} get a valid date, this whole block
is ignored.
document.write('<B>URL: </B>' Write the URL of the current
+ document.location.href + document given by the value
'</FONT><P>'); returned by the JavaScript
variable document.location.href
// done hiding from old browsers --> End of the footer code block.
</SCRIPT>
<!-- end of Volcano Web standard footers
-->
Most of the dynamic content in this examples comes from "properties"
of different JavaScript "objects", namely in this case the document object.
Each HTML document has built-in identifying pieces of information-- namely
it's title, date of last modification, URL, etc. We can query
the document object to get and then use this information.Table3.5 Explain Java
Script Footer
Information we are writing to the page using document.write that is
fixed content (strings of text in quotes) and information that is stored in
JavaScript variables, like document.title, we join with the "+" sign:
'Here is some fixed <b>HTML</b> text for the page:' + document.title
+ '! Nice, eh?'
The "+" sign joins the text together into one longer string, so if we were
using it in this lesson page, we would see:

Here is some fixed HTML text for the page: 27b.


JavaScript- Dynamic Content! Nice, eh?

Our JavaScript footer also uses a "conditional" test ("if this then do
that") for the modification date, that looks like:
if ( some condition to test ) {
JavaScript statement1;
JavaScript statement2;
:
:

138
JavaScript statementN;
}
which means that if the condition test in the first line's parenthesis
results in a TRUE value, we would follow the steps inside the "{" and "}"
brackets; if the test is FALSE, we skip these statements. With the power of
JavaScript, we can construct very complex conditional tests, but for now we
will keep it simple.
3.12 Stacking Elements
 The top and left properties determine the position of an element on the
display screen, which is a two-dimensional device
 Can create the appearance of a third dimension by having overlapping
elements, one of which covers the others (like windows)
o Done with the z-index property, which determines which
element is in front and which are covered by the front element
o The JavaScript variable associated with the z-index property
is zIndex
 The stacking order can be changed dynamically
 Make the elements anchors, so they respond to mouse clicking
o The href attribute can be set to call a JavaScript function by
assigning it the call, with 'JAVASCRIPT' attached to the call
code
o <a href = "JAVASCRIPT:fun()">
 The handler function must change the zIndex value of the element
 A call to the function from an element sets the zIndex value of the new
ontop element to 10 and the zIndex value of the old ontop element to 0
o It also sets the current ontop to the new ontop
Example:
<!DOCTYPE html>
<!-- stacking.html
Uses stacking.js
Illustrates dynamic stacking of images
-- >
<html Lang = "en">
<head>
<title> Dynamic stacking of images </title>

139
<meta charset = "utf-8" />
<script type = "text/javascript" src = "stacking.js" >
</script>
<style type = "text/css">
.plane1 {position: absolute; top: 0; left: 0;
z-index: 0;}
.plane2 {position: absolute; top: 50px; left: 110px;
z-index: 0;}
.plane3 {position: absolute; top: 100px; left: 220px;
z-index: 0;}
</style>
</head>
<body>
<p>
<img class = "plane1" id = "airplane1"
src = "airplane1.jpg"
alt = "(Picture of an airplane)"
onclick = "toTop('airplane1')" />
<img class = "plane2" id = "airplane2"
src = "airplane2.jpg"
alt = "(Picture of an airplane)"
onclick = "toTop('airplane2')" />
<img class = "plane3" id = "airplane3"
src = "airplane3.jpg"
alt = "(Picture of an airplane)"
onclick = "toTop('airplane3')" />
</p>
</body>
</html>
// stacking.js
// Illustrates dynamic stacking of images
var topp = "airplane3";
// The event handler function to move the given element
// to the top of the display stack

140
function toTop(newTop) {
// Set the two dom addresses, one for the old top
// element and one for the new top element
var domTop = document.getElementById(topp).style;
var domNew = document.getElementById(newTop).style;
// Set the zIndex properties of the two elements, and
// reset top to the new top
domTop.zIndex = "0";
domNew.zIndex = "10";
topp = newTop;
}
3.13 Locating the Mouse Cursor
An event is a notification about something specific that has occurred
because of browser user action, such as mouse click on a form button, radio
button etc. Strictly speaking event is an object that is implicitly created by the
browser and the JavaScript system in response to something happened. Event
object includes information about the event. For example mouse-click is one
such event. Whenever user mouse-click on the document, event object is
created which includes information like where and on which element event has
occurred. A mouse-click event defines two pairs of properties that give
geometric coordinates of the position of the element in the display that created
the event. One pair of the coordinates, clientX and clientY gives the
coordinates of the document display relative to the upper-left corner of the
browser display window, in pixels. The other pair, screen and screenY gives
coordinates of the element but relative client computer’s screen. In the
following example, every time user clicks the mouse button an alter box
displays the clientX, clientY, screenX and screen coordinates. The handler
show coords with event as parameter is triggred by the onclick attribute of the
body element.

<?xml version = "1.0" encoding = "utf-8"?>


<!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN"

141
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<!—mouse.html -- >
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function show_coords(event)
{
x=event.clientX;
y=event.clientY;
x1=event.screenX;
y1=event.screenY;
alert("ClientX coords: " + x + ", ClientY coords: " + y + ",ScreenX coords:
" + x1 + ", ScreenY coords: " + y1);
}
</script>
</head>
<body onclick="show_coords(event)">
<p>Click in the document. An alert box will alert the x and y coordinates of
the cursor.</p>
</body>
</html>
Reacting to a Mouse Click
A mouse click can be used to trigger an action, no matter where the
mouse cursor is in the display „ Use event handlers for onmousedown and
onmouseup for the document object to effect the action. „ In the example, the
action is to change the visibility attribute of a message „
Slow Movement of Elements: To animate an element, it must be moved
by small amounts, many times, in rapid succession „ JavaScript has two ways
to do this, but we cover just one: setTimeout("fun()", n) „ fun() is called, then a
delay of n milliseconds, then repeat the call.
3.14 Draggin and Dropping elements
Introduction to JavaScript Drag and Drop
Support for drag and drop operations is implemented in JavaScript and may
be applied to individual elements of your HTML page. For drag operations, an
element can handle the following JavaScript events:
 ondragstart
 ondrag
 ondragend

142
The ondragstart event initiates the drag operation. You can provide a
handler for this event to initiate or cancel drag operations selectively. To cancel
a drag operation, call the preventDefault method of the event object. To handle
an event, assign a value to the effectAllowed property and put the data for the
drag in thedataTransfer object, which you can get from the event object.
See Changing Drag Effects for information on theeffectAllowed property.
See Manipulating Dragged Data for information on handling the drag data.
Once a drag is under way, the ondrag event is fired continuously at the
element to give it a chance to perform any tasks it wants to while the drag is in
progress. Upon completion of the operation, the element receives
theondragend event. If the drag was successful, the ondrop handler for the drop
target element is also called (before the ondragend handler is called).
While a drag is in progress, events are sent to elements that are potential
drop targets for the contents being dragged. Those elements can handle the
following events:
 ondragenter
 ondragover
 ondragleave
 ondrop
The ondragenter and ondragleave events let the element know when the
user’s mouse enters or leaves the boundaries of the element. You can use these
events to change the cursor or provide feedback as to whether a drop can occur
on an element. The ondragover event is sent continuously while the mouse is
over the element to give it a chance to perform any needed tasks. If the user
releases the mouse button, the element receives anondrop event, which gives it
a chance to incorporate the dropped content.
If you implement handlers for the ondragenter and ondragover events,
you should call the preventDefaultmethod of the event object. This method
takes no parameters and notifies WebKit that your handler will act as the
receiver of any incoming data. If you do not call this method, WebKit receives
the data and incorporates it for you. You do not need to call preventDefault if
you simply want to be notified when the events occur.
Note: You must, at minimum, implement ondragover and call the prevent
Default method on the event object. If you do not do this, you will not receive
any of these four events.
Adding Handlers to Elements
You can add handlers for drag and drop events to any element in a
webpage. When a drag or drop operation occurs, WebKit looks for the

143
appropriate handler on the element that is the focus of the operation. If that
element does not define a handler, WebKit walks up the list of parent elements
until it finds one that does. If no element defines a handler, WebKit applies the
default behavior. To demonstrate this process, suppose you have the following
basic HTML in a webpage:

<body ondragstart="BodyDragHandler()"

ondragend="BodyDragEndHandler()">

<span ondragstart="SpanDragHandler()">Drag this text.</span>

</body>

If a user initiates a drag operation on the text in the span tag, WebKit
calls SpanDragHandler to handle the event. When the drag operation finishes,
WebKit calls the BodyDragEndHandler to handle the event.
Making an Element Draggable
WebKit provides automatic support to let users drag common items,
such as images, links, and selected text. You can extend this support to include
specific elements on an HTML page. For example, you could mark a
particulardiv or span tag as draggable.
To mark an arbitrary element as draggable, add the -webkit-user-
drag attribute (previously -khtml-user-drag) to the style definition of the
element. Because it is a cascading style sheet (CSS) attribute, you can include it
as part of a style definition or as an inline style attribute on the element tag. The
values for this attribute are listed in Table 3.6.
Table 3.6 Values for -web kit-user-drag attribute
Value Description
none Do not allow this element to be dragged.
element Allow this element to be dragged.
auto Use the default logic for determining whether the element should be
dragged. (Images, links, and text selections can be dragged but all
others cannot.) This is the default value.
The following example shows how you might use this attribute in
a span tag to permit the dragging of the entire tag. When the user clicks on

144
the span text, WebKit identifies the span as being draggable and initiates the
drag operation.

<span style="color:rgb(22,255,22); -webkit-user-drag:element;">draggable


text</span>

Manipulating Dragged Data


When an event occurs, your handler uses the dataTransfer object
attached to the event to get and set the clipboard data. This object defines
the clearData, getData, and setData methods to allow you to clear, get, and set
the data on the dragging pasteboard.
Note: For security purposes, the getData method can be called only from within
the ondrop event handler.
Unlike many other browsers, the WebKit drag-and-drop implementation
supports data types beyond those that are found in HTML documents. When
you call either getData or setData, you specify the MIME type of the target
data. For types it recognizes, WebKit maps the type to a known pasteboard
type. However, you can also specify MIME types that correspond to any
custom data formats your application understands. For most drag-and-drop
operations, you will probably want to work with simple data types, such as
plain text or a list of URIs.
Like applications, WebKit supports the ability to post the same data to
the pasteboard in multiple formats. To add another format, you simply call
the setData method with a different MIME type and a string of data that
conforms to that type.
To get a list of types currently available on the pasteboard, you can use
the types property of the dataTransferobject. This property contains an array of
strings with the MIME types of the available data.
Changing Drag Effects
When dragging content from one place to another, it might not always
make sense to move that content permanently to the destination. You might
want to copy the data or create a link between the source and destination
documents instead. To handle these situations, you can use the effect
Allowed and drop Effect properties of the data Transfer object to specify how
you want data to be handled.
The effect Allowed property tells Web Kit what types of operation the
source element supports. You would typically set this property in your on drag
start event handler. The value for this property is a string, whose value can be
one of those listed in Table 3.7.

145
Table 3.7 Options for dragging and dropping an element
Value Description
none No drag operations are allowed on the element.
copy The contents of the element should be copied to the destination
only.
link The contents of the element should be shared with the drop
destination using a link back to the original.
move The element should be moved to the destination only.
copyLink The element can be copied or linked.
copyMove The element can be copied or moved. This is the default value.
linkMove The element can be linked or moved.
all The element can be copied, moved, or linked.
The dropEffect property specifies the single operation supported by the
drop target (copy, move, link, ornone). When an element receives
an ondragenter event, you should set the value of this property to one of those
values, preferably one that is also listed in the effectAllowed property. If you
do not specify a value for this property, WebKit chooses one based on the
available operations (as specified in effectAllowed). Copy operations have
priority over move operations, which have priority over link operations.
When these properties are set by the source and target elements,
WebKit displays feedback to the user about what type of operation will occur if
the dragged element is dropped. For example, if the dragged element supports
all operations but the drop target only supports copy operations, WebKit
displays feedback indicating a copy operation would occur.
Changing the Appearance of Dragged Elements
During a drag operation, WebKit provides feedback to the user by
displaying an image of the dragged content under the mouse. The default image
used by WebKit is a snapshot of the element being dragged, but you can change
this image to suit your needs.
Changing the Snapshot With CSS
The simplest way to change the drag-image appearance is to use
cascading style sheet entries for draggable elements. WebKit defines the -
webkit-drag (formerly -khtml-drag) pseudoclass, which you can use to modify
the style definitions for a particular class during a drag operation. To use this
pseudoclass, create a new empty style-sheet class entry with the name of the

146
class you want to modify, followed by a a colon and the string -webkit-drag. In
the style definition of this new class, change or add attributes to specify the
differences in appearance between the original element and the element while it
is being dragged.
The following example shows the style-sheet definition for an element.
During normal display, the appearance of the element is determined by the
style-sheet definition of the divSrc4 class. When the element is dragged,
WebKit changes the background color to match the color specified in
the divSrc4:-webkit-drag pseudoclass.

#divSrc4 {

display:inline-block;

margin:6;

position:relative;

top:20px;

width:100px;

height:50px;

background-color:rgb(202,232,255);

#divSrc4:-webkit-drag {

background-color:rgb(255,255,154)

Specifying a Custom Drag Image


Another way to change the drag image for an element is to specify a
custom image. When a drag operation begins, you can use the

147
setDragImage method of the dataTransfer object. This method has the
following definition:

function setDragImage(image, x, y)

The image parameter can contain either a JavaScript Image object or


another element. If you specify an Image object, WebKit uses that image as the
drag image for the element. If you specify an element, WebKit takes a snapshot
of the element you specify (including its child elements) and uses that snapshot
as the drag image instead.
The x and y parameters of setDragImage specify the point of the image
that should be placed directly under the mouse. This value is typically the
location of the mouse click that initiated the drag, with respect to the upper-left
corner of the element being manipulated.
Unfortunately, obtaining this information in a cross-browser fashion is
easier said than done. There is no standard way to determine the position of the
mouse relative to the document because different browsers implement the
standard event values in subtly incompatible ways.
For the purposes of Safari and WebKit, clientX and clientY are
document relative, as are pageX and pageY(which are thus always equal
to clientX and clientY).
Obtaining the position of the element under the mouse is somewhat
easier. QuirksMode has a page (with code samples) on the subject
at http://www.quirksmode.org/js/findpos.html.
Complete Example
No description of drag and drop would be complete without a working
example. Save this into an HTML file and open it in Safari. You should see a
very simple set of boxes containing words. If you drag each word box into the
blue “target” box, the box will disappear and the word will appear in its correct
place to form the phrase “This is a test”.

<!DOCTYPE html>

<html>

<head>

<title>Drag and Drop</title>

148
<script><!--

var dragitem = undefined;

function setdragitem(item, evt) {

dragitem=item;

// alert('item: '+item);

// item is an HTML DIV element.

// evt is an event.

// If the item should not be draggable, enable this next line.

// evt.preventDefault();

return true;

function cleardragitem() {

dragitem=undefined;

// alert('item: '+item);

function dodrag() {

// alert('item: '+dragitem);

149
// This is required---used to tell WebKit that the drag should

// be allowed.

function handledragenter(elt, evt) {

evt.preventDefault();

return true;

function handledragover(elt, evt) {

evt.preventDefault();

return true;

function handledragleave(elt, evt) {

function handledrop(elt, evt) {

// alert('drop');

dragitem.style.display="none";

var newid=dragitem.id + '_dest';

var dest = document.getElementById(newid);

dest.innerHTML = dragitem.innerHTML;

150
}

// --></script>

<style><!--

.wordbox { border: 1px solid black; text-align: center; width: 50px; float:
left; -webkit-user-drag: element; -webkit-user-select: none; }

.spacer { clear: both; }

.target { margin-top: 30px; padding: 30px; width: 70px; border: 1px solid
black; background: #c0c0ff; margin-bottom: 30px; -webkit-user-drop:
element; }

.word { margin: 30px; min-height: 30px; border-bottom: 1px solid


black; width: 50px; float: left; }

--></style>

</head>

<body>

<p>Drop words onto target area to put them in their places.</p>

<div class='wordbox' id='this' ondragstart='setdragitem(this, event);'


ondrag='dodrag();' ondragend='cleardragitem();'>This</div>

<div class='wordbox' id='is' ondragstart='setdragitem(this, event);'


ondrag='dodrag();' ondragend='cleardragitem();'>is</div>

<div class='wordbox' id='a' ondragstart='setdragitem(this, event);'


ondrag='dodrag();' ondragend='cleardragitem();'>a</div>

<div class='wordbox' id='test' ondragstart='setdragitem(this, event);'


ondrag='dodrag();' ondragend='cleardragitem();'>test</div>

151
<div class='spacer'></div>

<div class='target' ondragenter='handledragenter(this, event);'


ondragover='handledragover(this, event);'
ondragleave='handledragleave(this, event);' ondrop='handledrop(this,
event);'>TARGET</div>

<div class='words'>

<div class='word' id='this_dest'></div>

<div class='word' id='is_dest'></div>

<div class='word' id='a_dest'></div>

<div class='word' id='test_dest'></div>

</div>

</body>

</html>

152
NOTES
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………

153
UNIT - IV
XML and Web services
In This Chapter
 Introduction
 XML documents structure
 Document Type Definition
 Namespace
 XML schemas
 Displaying Raw XML Document
 Displaying XML Document with CSS
 XSLT Style Sheet
 XML Processors
 Web services.
XML and Web services
A Web Service is a standards-based, language-agnostic software entity
that accepts specially formatted requests from other software entities on remote
machines via vendor and transport neutral communication protocols producing
application specific responses.
4.1 Introduction to Web Services
Web services are application components
Web services communicate using open protocols
Web services are self-contained and self-describing
Web services can be discovered using UDDI
Web services can be used by other applications
HTTP and XML is the basis for Web services
Interoperability has Highest Priority
When all major platforms could access the Web using Web browsers,
different platforms couldn't interact. For these platforms to work together,
Web-applications were developed.
Web-applications are simply applications that run on the web. These are
built around the Web browser standards and can be used by any browser on any
platform. Web Services take Web-applications to the Next Level By using Web
services, your application can publish its function or message to the rest of the
world. Web services use XML to code and to decode data, and SOAP to
transport it (using open protocols). With Web services, your accounting

154
department's Win 2k server's billing system can connect with your IT supplier's
UNIX server.
Web Services have Two Types of Uses
Reusable Application - Components
There are things applications needs very often. So why make these over
and over again?
Web services can offer application-components like: currency
conversion, weather reports, or even language translation as services.
Connect existing software.
Web services can help to solve the interoperability problem by giving
different applications a way to link their data.
With Web services you can exchange data between different
applications and different platforms.
Benefits of Web Services
Loosely Coupled
Each service exists independently of the other services that make up the
application. The Individual pieces of the application have to be modified
without impacting unrelated areas.
Ease of Integration
Data is isolated between applications creating ’silos’. Web Services act
as glue between these and enable easier communications within and across
organizations.
Service Reuse
Takes code reuse a step further. A specific function within the domain is
only ever coded once and used over and over again by consuming applications.
4.2 XML Document Structure
The XML Recommendation states that an XML document has both
logical and physical structure. Physically, it is comprised of storage units called
entities, each of which may refer to other entities, similar to the way
that includes works in the C language. Logically, an XML document consists of
declarations, elements, comments, character references, and processing
instructions, collectively known as the markup.
An XML document consists of three parts, in the order given:
An XML declaration (which is technically optional, but recommended
in most normal cases)

155
A document type declaration that refers to a DTD (which is optional,
but required if you want validation)
A body or document instance (which is required)
Collectively, the XML declaration and the document type declaration
are called the XML prolog.
XML Declaration
The XML declaration is a piece of markup (which may span multiple
lines of a file) that identifies this as an XML document. The declaration also
indicates whether the document can be validated by referring to an external
Document Type Definition (DTD). DTDs are the subject of chapter 4; for now,
just think of a DTD as a set of rules that describes the structure of an XML
document.
The minimal XML declaration is:
<? Xml version="1.0" ?>
XML is case-sensitive (more about this in the next subsection), so it's
important that you use lowercase for xml and version. The quotes around the
value of the version attribute are required, as are the? Characters. At the time of
this writing, "1.0" is the only acceptable value for the version attribute, but this
is certain to change when a subsequent version of the XML specification
appears.
In most cases, this XML declaration is present. If so, it must be the very
first line of the document and must not have leading white space. This
declaration is technically optional; cases where it may be omitted include when
combining XML storage units to create a larger, composite document.
Actually, the formal definition of an XML declaration, according to the
XML 1.0 specification is as follows:
XMLDecl ::= '<?xml' Version Info EncodingDecl? SDDecl? S? '?>'
This Extended Backus-Naur Form (EBNF) notation, characteristic of
many W3C specifications, means that an XML declaration consists of the
literal sequence '<?xml', followed by the required version information, followed
by optional encoding and standalone declarations, followed by an optional
amount of white space, and terminating with the literal sequence '?>'. In this
notation, a question mark not contained in quotes means that the term that
precedes it is optional.
XML Structure
This page provides a description of XML structure including the
document parts, the prologue, and provides a simple XML example document.

156
Document Parts
Prolog
Document Element (root element)
The Prologue
The prologue, equivalent to the header in HTML, may include the following:
An XML declaration (optional) such as:
<? Xml version="1.0"?>
A DTD or reference to one (optional). An example reference to an external
DTD file:
<! DOCTYPE LANGLIST SYSTEM "langlist.dtd">
Processing instructions - An example processing instruction that causes style to
be determined by a style sheet:
<? Xml-style sheet type="text/css" href="xmlstyle.css"?>
An XML Document
Therefore a complete well formed XML document may look like:
<? Xml version="1.0"?>
<LAND>
<FOREST>
<TREE>Oak</TREE>
<TREE>Pine</TREE>
<TREE>Maple</TREE>
</FOREST>
<MEADOW>
<GRASS>Bluegrass</GRASS>
<GRASS>Fescue</GRASS>
<GRASS>Rye</GRASS>
</MEADOW>
</LAND>
The LAND element, above, is the root element.
4.3 Document Type Definition
A document type definition (DTD) is a set of markup declarations that
define a document type for an SGML-family markup language (SGML, XML,
and HTML). A Document Type Definition (DTD) defines the legal building
blocks of an XML document. It defines the document structure with a list of
legal elements and attributes.

157
Document Type Definition (DTD) Definition
A Document Type Definition (DTD) is a specific document defining
and constraining definition or set of statements that follow the rules of the
Standard Generalized Markup Language (SGML) or of the Extensible Markup
Language (XML), a subset of SGML. A DTD is a specification that
accompanies a document and identifies what the funny little codes (or markup)
are that, in the case of a text document, separate paragraphs, identify topic
headings, and so forth and how each is to be processed. By mailing a DTD with
a document, any location that has a DTD "reader" (or "SGML compiler") will
be able to process the document and display or print it as intended. This means
that a single standard SGML compiler can serve many different kinds of
documents that use a range of different markup codes and related meanings.
The compiler looks at the DTD and then prints or displays the document
accordingly.
The document you are looking at is coded in a particular DTD
called HTML. In this case, the "compiler" or document handler is your Web
browser which is designed to handle text documents encoded with HTML tags.
(Other programs could be developed that would handle HTML and other DTDs
as well.)
IBM and many large and small corporations are converting documents
to SGML or, more recently, to XML, each with its own company document
type definition or set of definitions. For corporate intranets and extranets, the
document type definition of HTML provides one new "language" that everyone
can format documents in and read universally.
4.4 What Is a Namespace?
A namespace is a set of names in which all names are unique. For
example, the names of my children could be thought of as a namespace, as
could the names of California corporations, the names of C++ type identifiers,
or the names of Internet domains. Any logically related set of names in which
each name must be unique is a namespace.
Namespaces make it easier to come up with unique names. Imagine
how hard it would be to name your next child if the name had to be unique
across the face of the earth. Restricting uniqueness to a more limited context,
like my set of children, simplifies things tremendously. When I name my next
child, my only consideration is that I don't use the same name that I already
used for one of my other children. Another set of parents can choose the same
name I choose for one of their children, but those names will be part of distinct
namespaces and, therefore, can be easily distinguished.

158
Before a new name is added to a namespace, a namespace authority
must ensure that the new name doesn't already exist in the namespace. In some
scenarios this is trivial as it is in child naming. In others it's quite complex.
Today's many Internet naming authorities present a good example. If this step
is skipped, however, duplicate names will eventually corrupt the namespace,
making it impossible to refer to certain names without ambiguity. When this
happens, the set of names is no longer officially considered a namespace—by
definition a namespace must ensure the uniqueness of its members.
Namespaces themselves must also be given names in order to be useful.
Once a namespace has a name, it's possible to refer to its members. For
example, consider the sample namespaces shown in the two boxes in Figure 1.
The names of these sample namespaces are Microsoft and Acme Hardware,
respectively. Notice that even though both of these namespaces contain some of
the same local names, it's possible to refer to them without ambiguity through
namespace-qualified names, also shown in Figure 1.

Figure 4.1: Non-ambiguous namespaces


Namespaces in XML
Many developers feel that the XML 1.0 specification was incomplete
because it didn't offer namespace support. As a result, all names used in XML
documents belonged to one global namespace, making it very difficult to come
up with unique names.
Most developers, including the XML 1.0 authors themselves, knew that
this would eventually cause too much ambiguity in large XML-based
distributed systems. For example, consider the following XML document:
<Student>
<Id>3235329</id>
<Name>Jeff Smith</name>
<Language>C#</language>
<Rating>9.5</rating>

159
</student>
This document uses several names, each of which are quite
commonplace. The student element models a student of a software-training
course. The id, language, and rating elements model the student's database
record number, programming language of preference, and the rating the student
gave the course (out of 10). Each of these names will certainly be used in other
situations where they don't convey the same meaning.
4.5 What is an XML Schema?
An XML Schema is a language for expressing constraints about XML
documents. There are several different schema languages in widespread use,
but the main ones are Document Type Definitions (DTDs), Relax-NG,
Schematron and W3C XSD (XML Schema Definitions). From this page you
can find out more about DTDs and W3C XSD, since those are the primary
schema languages defined at W3C.
What is XML Schema used for?
A Schema can be used:
to provide a list of elements and attributes in a vocabulary;
to associate types, such as integer, string, etc., or more specifically such as
hatsize, sock_colour, etc., with values found in documents;
To constrain where elements and attributes can appear, and what can
appear inside those elements, such as saying that a chapter title occurs inside a
chapter, and that a chapter must consist of a chapter title followed by one or
more paragraphs of text;
To provide documentation that is both human-readable and machine-
process able;
To give a formal description of one or more documents.
Information in schema documents is often used by XML-aware editing
systems so that they can offer users the most likely elements to occur at any
given location in a document. Checking a document against a Schema is known
as validating against that schema; for a DTD, this is just validating, but for any
other type of schema the type is mentioned, such as XSD Validation or Relax-
NG validation.
Validating against a schema is an important component of quality
assurance.
The Service Modeling Language (SML) provides a framework for
relating multiple XSD documents to one or more documents in a single
validation episode.

160
Since XSD supports associating data types with element and attribute
content, it is also used for data binding, that is, for software components that
read and write XML representations of computer programming-language
objects.
Examples
Document Type Definitions are defined in the XML Recommendation.
They are very widely supported with a high degree of interoperability.
W3C XML Schema Definitions are defined in the W3C XML Schema
specification. This is in three parts, of which the first part, numbered zero, is an
introductory document.
What is XML Schema (XSD)?
XML Schema Definition (XSD) language is the current standard
schema language for all XML documents and data. On May 2, 2001, the World
Wide Web Consortium (W3C) published XSD in its version 1.0 format.
The XML Schema definition language (XSD) enables you to define the
structure and data types for XML documents. An XML Schema defines the
elements, attributes, and data types that conform to the World Wide Web
Consortium (W3C) XML Schema Part 1: Structures Recommendation for the
XML Schema Definition Language. The W3C XML Schema Part 2: Data types
Recommendation is the recommendation for defining data types used in XML
schemas. The XML Schema Reference (XSD) is based on the W3C 2001
Recommendation specifications for Data types and for Structures.
An XML Schema is composed of the top-level schema element.
The schema element definition must include the following namespace:
The schema element contains type definitions (simple Type and
complex Type elements) and attribute and element declarations.
In addition to its built-in data types (such as integer, string, and so on),
XML Schema also allows for the definition of new data types using the simple
Type and complex Type elements.
Simple Type
A type definition for a value of that can be used as the content (text
only) of an element or attribute. This data type cannot contain elements nor
have attributes.

161
Complex Type
Type definition elements that can to be contain the attributes and
elements. This data type can contain elements and have attributes.
In the remainder of this XSD Starter Kit, we will look at how to get
started with XSD. For in-depth learning or reading on XSD, refer to the
following draft recommendations that describe it:
XML Schema Part 0: Primer
XML Schema Part 1: Structures
XML Schema Part 2: Data types
4.6 Displaying RAW XML Documents
An XML enabled browser or any other system that can deal with XML
documents cannot possibly know how to format the tags defined in the doc.
without a style sheet that defines presentation styles for the doc tags the XML
doc cannot be displayed in a formatted manner.
Some browsers like FX2 have default style sheets that are used when
style sheets are not defined.
E.g. Of planes .xml document.
4.7 Displaying XML Documents with CSS
Style sheet information can be provided to the browser for an xml
document in two ways.
• First, a CSS file that has style information for the elements in the XML
document can be developed.
• Second the XSLT style sheet technology can be used.
Using CSS is effective; XSLT provides far more power over the
appearance of the documents display.
A CSS style sheet for an XML document is just a list of its tags and
associated styles
The connection of an XML document and its style sheet is made
through an xml style sheet processing instruction Display– used to specify
whether an element is to be displayed inline or in a separate block.
<? Xml-style sheet type = "text/css “href = “planes.css"?>
Displaying XML Document using CSS
CSS stands for Cascading Style Sheets. Styles define how to display
HTML elements. Styles are normally stored in Style Sheets. Styles were added
to HTML 4.0 to solve a problem. External Style Sheets can save a lot of work.
External Style Sheets are stored in CSS files. Multiple style definitions will
cascade into one.

162
A Cascading Style Sheet is a file that contains instructions for
formatting the elements in an XML document.
Creating and linking a CSS to your XML document is one way to tell
browser how to display each of document's elements. An XML document with
an attached CSS can be open directly in Internet Explorers. You don't need to
use an HTML page to access and display the data. There are two basic steps for
using a css to display an XML document:
Create the CSS file.
Link the CSS sheet to XML document.
Creating CSS file
CSS is a plain text file with .css extension that contains a set of rules
telling the web browser how to format and display the elements in a specific
XML document. You can create a css file using your favorite text editors like
Notepad, WordPad or other text or HTML editor as show below:
general.css
employees
{
background-color: #ffffff;
width: 100%;
}
id
{
display: block; margin-bottom: 30pt; margin-left: 0;
}
name
{
color: #FF0000;
font-size: 20pt;
}
city,state,zipcode
{
color: #0000FF;
font-size: 20pt;
}
Linking
To link to a style sheet you use an XML processing directive to
associate the style sheet with the current document. This statement should
occur before the root node of the document.

163
<? Xml-style sheet type="text/css" href="styles/general.css">
The two attributes of the tag are as follows:
Href
The URL has the style sheet.
Type
The MIME type of the document begin linked, which in this case is
text/css. MIME stands for Multipart Internet Mail Extension. It is a standard
which defines how to make systems aware of the type of content being included
in e-mail messages. The css file is designed to attach to the XML document as
shown below:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!--This xml file represent the details of an employee-->
<?xml-style sheet type="text/css" href="styles/general.css">
<employees>
<employee id="1">
<name>
<first Name>Mohit</first Name>
<last Name>Jain</last Name>
</name>
<city>Karnal</city>
<state>Haryana</state>
<zip code>98122</zip code>
</employee>
<employee id="2">
<name>
<first Name>Rahul</first Name>
<last Name>Kapoor</last Name>
</name>
<city>Ambala</city>
<state>Haryana</state>
<zip code>98112</zip code>
</employee>
</employees>
4.8 XSLT Style Sheet
XLST is an XML – related technology that is used to manipulate and
transform XML documents. The acronym XSLT stands for Extensible Style
sheet Language Transformations, which is a mouthful to say, but it sounds
more complicated than it is.

164
A language for transforming XML documents into other XML
documents
Designed for use both as part of XSL and independently of XSL
Not intended as a completely general-purpose XML transformation
language.[W3C XSLT Recommendation]
Advantages and Disadvantages
Advantages
Easy to merge data into XML data into a presentation
More resilient to change in the details of the XML document than in the low-
level DOM (Document Object Model) and SAX (Simple API for XML)
Database inquiries can be returned in XML
Insensitive to column order
Disadvantages
Memory intensive and suffers a performance penalty
Difficult to implement complicated business rules
Have to learn a new language
Can’t change the value of variables (requires recursion)
XSL Transformations
Use
X-Path to identify (select) parts of an XML document
XSLT Templates to apply transformations
Requires
Well formed XML document
XSL document (style sheet) that contains formatting and transformation
templates
XSLT parser to perform the transformations
Steps for Translating a Document
Tell a system which parser to use
Establish a factory in which to create transformations
Create a transformer for a particular style sheet
Invoke the transformer to process the document.
4.9 XML Processors
An XML processor is a necessary piece of the XML puzzle. The XML
processor takes the XML document and DTD and processes the information so
that it may then be used by applications requesting the information.

165
A software program reads an xml document and takes actions
accordingly; this is called processing the xml. Any program that can read and
process xml documents is known as an xml processor. An xml processor reads
the xml file and turns it into in-memory structures that the rest of the program
can access.
The most fundamental xml processor reads an xml document and
converts it into an internal representation for other programs or subroutines to
use. This is called a parser, and it is an important component of every xml
processing program.
Types
XML processors are classified as validating or non-validating types,
depending on whether or not they check XML documents for validity. A
processor that discovers a validity error must be able to report it, but may
continue with normal processing.
A few validating parsers are: xml4c (IBM, in C++), xml4j (IBM, in
Java), MSXML (Microsoft, in Java), TclXML (TCL), xmlproc (Python),
XML::Parser (Perl), Java Project X (Sun, in Java).
A few non-validating parsers are: OpenXML (Java), Lark (Java), xp
(Java), AElfred (Java), expat (C), XParse (JavaScript), xmllib (Python).
XML stands for Extensible Markup Language and is a text-based
markup language derived from Standard Generalized Markup Language
(SGML).
XML tags identify the data and used to store and organize data, rather
than specifying how to display it like HTML tags are used to display the data.
XML is not going to replace HTML in the near but introduces new possibilities
by adopting many successful features of HTML.
There are three important characteristics of XML that make it useful in
a variety of systems and solutions:
XML is extensible: XML essentially allows you to create your own
language, or tags, that suit your application.
XML separates data from presentation: XML allows you to store
content with regard to how it will be presented.
XML is a public standard: XML was developed by an organization
called the World Wide Web Consortium (W3C) and available as an open
standard.

166
XML Usage
A short list of XML's usage says it all:
XML can work behind the scene to simplify the creation of HTML
documents for large web sites.
XML can be used to exchange of information between organizations
and systems.
XML can be used for offloading and reloading of databases.
XML can be used to store and arrange data in a way that is
customizable for your needs.
XML can easily be mixed with style sheets to create almost any output
desired.
Virtually any type of data can be expressed as an XML document.
What is Markup?
XML is not itself a markup language rather it is a set of rules for
building markup languages. So what exactly is a markup language? Markup is
information added to a document that enhances its meaning in certain ways, in
that it identifies the parts and how they relate to each other. More specifically, a
markup language is a set of symbols that can be placed in the text of a
document to demarcate and label the parts of that document.
Following is an example of how XML markup looks when embedded in
a piece of text:
<Message>
<Text>Hello, word! </text>
</message>
This snippet includes the markup symbols, or you can call them tags
and they are <message>...</message> and <text>... </text>. The tags
<message> and </message> mark the start and end points of the whole XML
fragment. The tags <text> and </text> surround the text Hello, world!
Is XML a Programming Language?
A programming language is a vocabulary and syntax for instructing a
computer to perform specific tasks. XML doesn't qualify as a programming
language because it doesn't instruct a computer to do anything, as such. It's
usually stored in a simple text file and is processed by special software that's
capable of interpreting XML.

167
Syntax
This chapter takes you through the simple syntax rules to be followed to
write a XML document. Following is a complete (but very simple) XML
document:
<? Xml version="1.0"?>
<Contact-info>
<Name>Tanmay Patil</name>
<Company>Tutorials Point</company>
<Phone> (011) 123-4567</phone>
</contact-info>
You can notice there are two kinds of information in the above
example:
markup, like <contact-info> and
Text (also known as character data), like Tutorials Point and (011) 123-
4567.
The following diagram depicts the syntax rules to write different kinds of
markup and text in an XML document.

Figure 4.2: Syntax rules to write different kinds of markup and text
in an XML document
Let us see each of the above points in detail in the following sections.
XML Declaration
The XML document can optionally have a XML declaration. The XML
declaration is written as below:
<? Xml version="1.0" encoding="UTF-8"?>
Where version is the XML version and encoding specify the character
encoding used in the document.

168
Syntax Rules for XML declaration
The XML declaration is case sensitive i.e it may not begin with
"<?XML" or any other variant.
If you specify the XML declaration, then it must be the first statement
in the XML document.
An HTTP protocol can override the encoding value that you put in the
XML declaration.
Tags and Elements
A xml file is structured by several xml-elements, also called xml-nodes
or xml-tags. The xml-element name is enclosed by < > brackets as shown
below:
<Element>
Syntax Rules for Tags and Elements
(1) Element Syntax: Each xml-element needs to close as shown below. Either
with start and end elements:
<Element>....</element>
(or) for simple-cases just this way:
<element/>
(2) Nesting of elements: A xml-element can contain additional children xml-
elements inside it. But the elements may not overlap i.e an end tag must always
have the same name as the most recent unmatched start tag.
Following example shows wrong nested tags:
<? Xml version="1.0"?>
<Contact-info>
<Company>Tutorials Point
<Contact-info>
</company>
Following example shows correct nested tags:
<? Xml version="1.0"?>
<Contact-info>
<Company>Tutorials Point</company>
<Contact-info>
(3) Root element: A XML document can have only one root element. For
example following is not a well-formed XML document, because both the x
and y elements occur at the top level:

169
<x>...</x>
<y>...</y>
The following example shows a well formed XML document:
<Root>
<x>...</x>
<y>...</y>
</root>
(4) Case sensitivity: The names of xml-elements are case-sensitive. That
means the name of start and end elements need to be written in the same case.
For example <contact-info> is different from <Contact-Info>.
Attributes
An xml-element can have one or more attributes. An attribute specifies a
single property for the element, using a name/value pair. For example:
<a href="http://www.tutorialspoint.com/">Tutorialspoint!</a>
Syntax Rules for XML Attributes
(1) - Attribute names in XML (unlike HTML) are case sensitive i.e HREF and
href refer to two different XML attributes.
(2) - Same attribute cannot have two values. The following example is not well-
formed because the b attribute is specified twice:
<a b="x" c="y" b="z">....</a>
(3) - An attribute name should not be defined in quotation marks, whereas
attribute values must always appear in quotation marks. Following example
demonstrates WRONG xml format:
<a b=x>....</a>
Here attribute value is not defined in quotation marks.
XML References
References usually allow you to add or include additional text or
markup in an XML document. References always begin with the
character "&" (which is especially reserved) and end with the character ";".
XML has two types of references:
(1) Entity References: An entity reference contains a name between the start
and end delimiters. For example & where amp is name. The name refers to a
predefined string of text and/or markup.
(2) Character References: These contain references, like &#65;, contains a
hash mark (“#”) followed by a number. The number always refers to the
Unicode code for a single character. In this case 65 refers to letter "A".

170
XML Text
(1) - The names of xml-elements and xml-attributes are case-sensitive which
means the name of start and end elements need to be written in the same case.
(2) - To avoid character encoding problems all xml files should be saved as
Unicode UTF-8 or UTF-16 files.
(3) - Whitespace characters like blanks, tabs and line-breaks between xml-
elements and between the xml-attributes will be ignored.
(4) - Some characters are reserved by the xml syntax itself. Hence they can't be
used directly. To use them some replacement-entities can be used which are
listed below:
Table 4.1: Replacement - entities

not allowed replacement-entity character


character description

< &lt; less than

> &gt; greater than

& &amp; ampersand

' &apos; apostrophe

" &quot; quotation mark

Documents
An XML document is a basic unit of XML information, composed of
elements and other markup in an orderly package. An XML document can
contain any data, say for example, database of numbers, or some abstract
structure representing a molecule or equation.
Example
A simple document would look like as in the following example:
<? Xml version="1.0"?>
<Contact-info>
<Name>Tanmay Patil</name>
<Company>Tutorials Point</company>
<Phone> (011) 123-4567</phone>

171
</contact-info>
As can been seen the following image depicts the XML parts.

Document Prolog Section


The document prolog comes at the top of the document, before the root
element. This section can further be divided into:
XML declaration
Document type declaration
We will learn more about XML declaration while studying XML Declaration.
Document Elements Section
Document Elements are the building blocks of XML. These divide the
document into a hierarchy of regions, each serving a specific purpose. You can
separate a document into parts so they can be rendered differently, or used by a
search engine. Elements can be containers, with a mixture of text and other
elements.
We will learn more about XML elements while studying XML
Elements.
Declaration
This chapter will discuss about the XML declaration. XML declaration
contains details that prepare an XML processor for working with a document. It
is optional in use but, when used, it must appear in first line of the XML
document.
Syntax
<? Xml
Version="version _ number"
Encoding="encoding _ declaration"
Standalone="standalone _ status"
?>
Each parameter consists of a parameter name, an equals sign (=), and
parameter value inside a quote. Following is the detail of the above syntax:

172
Parameter Parameter _value Parameter _description

Version 1.0 Specifies the version of the XML


standard used.

Encoding UTF-8, UTF-16, It defines the character encoding used


ISO-10646-UCS- in document. UTF-8 is the default
2, ISO-10646- encoding used.
UCS-4, ISO-8859-
1 to ISO-8859-9,
ISO-2022-JP, Shift
_JIS, EUC-JP

Standalone It's value is either It informs the parser whether the


yes or no. document relies on information from an
external source, such as external
document type definition (DTD), for its
content. The default value is no; setting
it to yes tells the processor there are no
external declarations required for
parsing the document.

Rules
An XML declaration should abide with the following rules:
If the XML declaration is present in the XML, it must be placed as first
line in the XML document.
f the XML declaration is included, it must contain the version number attribute.
Parameter names and values are case-sensitive.
The names are always lowercase.
The order of placing the parameters is important. The correct order is: version,
encoding, standalone
Either single or double quotes may be used.
The XML declaration has no closing tag i.e </?xml>
Following are few examples of XML declarations:
Example of XML declaration with no parameters defined.
<? Xml >
Example of XML declaration with version defined.
<? Xml version="1.0">

173
Tags
Now we are going to learn about one of the most important part of
XML, which is XML tags. XML tags form the base of an XML. They define
the boundaries of an element in the XML. They can also be used to insert
comments, declare settings for parsing the environment and insert special
instructions.
We can categorize XML tags as follows:
Start Tag
The beginning of every non-empty XML element is marked by a start-
tag. An example of start-tag is:
<Address>
End Tag
Every element that has a start tag should end with using an end-tag. An
example of end-tag is:
</address>
Note that the end tags include a solidus ("/") before the element's name.
Empty Tag
The text that appears between start-tag and end-tag is called content. An
element which has no element is termed as empty. Now an empty element can
be represented in two ways as below:
(1) Start-tag immediately followed by an end-tag as shown below:
<Hr></hr>
(2) It’s a complete empty-element tag as shown below:
<hr />
Empty-element tags may be used for any element which has no content.
XMl Tags Rules
Following are the rules that need to be followed for XML tags:
Rule 1
XML tags are case-sensitive. Following line of code is an example of
wrong syntax </Address>, because of the case difference observed in the word
"element" which is not allowed and gives error.
<Address>this is wrong syntax</Address>
Following code shows is a correct way where we used the same case to
name the start and end tag.
<Address>this is correct syntax</address>

174
Rule 2
XML tags must be closed in order i.e XML tag opened inside another
element must be closed before the outer element is closed. For example:
<outer_element>
<Internal _element>
This tag is closed before the outer_element
</internal _element>
</outer_element>
Elements
XML elements can be defined as building blocks of an XML. Elements
can behave as a container to hold text, elements, attributes, media objects or
mix of all.
Each XML document contains one or more elements, the boundaries of
which are either delimited by start-tags and end-tags, or, for empty elements, by
an empty-element tag.
Syntax
Following is the syntax to write an XML element:
<Element-name attribute1 attribute2>
....content
</element-name>
Where
Element-name is the name of the element. The name in the start and
end tag must match.
attribute1, attribute2 are attributes of the element separated by white
spaces. An attribute defines a property of the element. It associates a name with
a value, which is a string of character data. An attribute will have following
syntax:
Name = "value"
Name is followed by an = sign and a string value inside quotes (" " or ' ').
Empty Element
An empty element (element with no content) will have following syntax:
<name attribute1 attribute2.../>
Following is a simple example of XML document making use of various XML
element:
<? Xml version="1.0"?>

175
<Contact-info>
<address category="residence">
<Name>Tanmay Patil</name>
<Company>Tutorials Point</company>
<Phone> (011) 123-4567</phone>
<address/>
</contact-info>
XML Elements Rules
Following are the rules that need to be followed for XML elements:
An element name can contain any alphanumeric characters. The only
punctuation allowed in names are the hyphen (-), under-score (_) and period
( . ).
Names are case sensitive. For example Address, addresses, ADDRESS
are different names.
Element start and end tag should be identical.
An element which is a container can contain text or elements as seen in
the above example.
Attributes
This chapter discusses about the XML attributes. Attributes are part of
the XML elements. An element can have any number of unique attributes.
Attribute gives more information about the XML element or more precisely it
defines a property of the element. An XML attribute is always a name-
value pair.
Syntax
An XML attribute has following syntax:
<Element-name attribute1 attribute2 >
....content...
< /element-name>
Where attribute1 and attribute2 will have the following form:
Name = "value"
Value has be in double (" ") or single (' ') quotes.
Here attribute1 andattribute2 are unique attribute labels.
Attributes can be used to add a unique label to an element, place it in a
category, add a Boolean flag, or otherwise associate some short string of data.
Following example demonstrates the use of attributes:

176
<? Xml version="1.0" encoding="UTF-8"?>
<Garden>
<plants category="flowers">
<Rose>ROSE</rose>
<Lotus>LOTUS</lotus>
</plants>
<plants category="color">
<Red>RED</red>
<Pink>PINK</pink>
</plants>
</garden>
Attributes usually are used to distinguish between elements of the same
name say when you don't want to create a new element for every situation, so
an attribute can add a little more detail in differentiating two or more similar
types of elements.
In the above example we have categorized the plants by including
attributecategory and assigning different values to each of the elements. Hence
we have two categories of plants, one flowers and other color. Hence we have
two plant elements with different attributes.
Attribute Types
Following table lists the type of attributes:

Attribute Type Description

String Type May take any literal string as a value. CDATA is a


StringType. CDATA is character data. This means that any
string of non-markup characters is legal as part of the
attribute.

177
Tokenized These are more constrained type. The validity constraints
Type noted in the grammar are applied after the attribute value
has been normalized. There are following kinds of
Tokenized Type attribute types:
ID: This is used if you want to specify your element as
unique.
IDREF: This is used to reference an ID that has been
named for another element.
IDREFS: This is used to reference all IDs of an element.
ENTITY: This indicates that the attribute will represent an
external entity in the document itself.
ENTITIES: This indicates that the attribute will represent
an external entity in the document.
NMTOKEN: This is similar to CDATA with even more
restrictions on what data can be part of the attribute.
NMTOKENS: This is similar to CDATA with even more
restrictions on what data can be part of the attribute.

Enumerated These have a list of allowed values in their declaration. hey


Type must take one of those values. There are two kinds of
enumerated attribute types
Notation Type: It declares that an element will be
referenced to a NOTATION declared somewhere else in
the XML document.
Enumeration: Enumeration allows you to define a
specific list of values that the attribute value must match.

Element Attribute Rules


Following are the rules that need to be followed for attributes:
An attribute name must not appear more than once in the same start-tag
or empty-element tag.
The attribute must have been declared; the value must be of the type
declared for it.
Attribute values must not contain direct or indirect entity references to
external entities.
The replacement text of any entity referred to directly or indirectly in an
attribute value must not contain either less than sign <
Comments
This chapter explains how a comment works in XML documents. XML
comments are similar to HTML comments. Comments are added as notes or
lines for understanding purpose of a XML code.

178
Comments can be used to include related links, information and terms.
Comments can be viewed only in the source code not in the XML code.
Comments may appear anywhere in the XML code.
Syntax
XML comment has the following syntax:
<! -------Your comment----->
Comments start with <! ---and ends with--->. You can add textual notes
as a comment between the characters. Never nest one comment with other
comment.
Example
Following example demonstrates the use of comments in XML document:
<? Xml version="1.0" encoding="UTF-8”?>
<! ---Students grades are uploaded by months---->
<Class _ list>
<Student>
<Name>Tanmay</name>
<Grade>A</grade>
</student>
</class _ list>
Any text between <! -- And --> section is considered as an comment and you
can include anything you want.
XML Comments Rules
Following are the rules that need to be followed for XML comments:
Comments cannot appear before XML declaration.
Comments may appear anywhere in a document.
Comments cannot appear before an Element tag.
Comments must not appear within attribute values.
Comments cannot be nested one inside the another.
Character Entities
This chapter discusses the XML Character Entities. But before we
understand Character Entities, let us first understand what an XML entity is.
As put by W3 Consortium the definition of entity is as follows:
The document entity serves as the root of the entity tree and a starting-
point for an XML processor.

179
This means entities are placeholders in XML. These can be declared in
the document prolog or in a DTD. There are different types of entities and this
chapter will discuss on character entity.
Character Entities are used to name some of the entities which are
symbolic representation of information i.e characters that are difficult or
impossible to type can be substituted by Character Entities.
Types of Character Entities
There are three types of character entities:
Predefined Character Entities
Numbered Character Entities
Named Character Entities
Predefined Character Entity
These are introduced to avoid the ambiguity while using some of
symbols. For example ambiguity observed when less than (<) or greater than (
> ) symbol is used with the angle tag(<>). These are basically used to delimit
tags in XML. Following is a list of pre-defined character entities from XML
specification. These can be used to express characters safely.
ampersand: &amp;
Single quote: &apos;
Greater than: &gt;
Less than: &lt;
Double quote: &quot;
Numeric Character Reference
To refer the character entity numeric reference can be used. Numeric
reference can either be in decimal or hexadecimal numbers. As there are
thousands of numeric references present, these are bit harder to remember.
Numeric reference refers to the character by its number in the Unicode
character set.
General syntax for decimal numeric reference is:
&# decimal number;
General syntax for hexadecimal numeric reference is:
&#x Hexadecimal number;
Following table list some of the predefined character entities with their numeric
values:

180
Entity Character Decimal Hexadecimal
name reference reference

quot " &#34; &#x22;

amp & &#38; &#x26;

apos ' &#39; &#x27;

lt < &#60; &#x3C;

gt > &#62; &#x3E;

Named Character Entity


As it’s hard to remember the numeric characters, the most preferred
type of character entity is the named character entity. Here each entity is been
identified with a name.
For example:
'Aacute' represents capital character with acute accent.
'ugrave' represents the small with grave accent.
CDATA Sections
This chapter discusses the XML CDATA section. CDATA means
Character Data. CDATA are used to escape block of text that does not parsed
by the parser and are otherwise recognized as markup.
Predefined entities such as &lt;, &gt;, and &amp; require typing and are
generally hard to read in the markup. For such cases CDATA section can be
used. By using CDATA section, you are commanding the parser that this
section of the document contains no markup and should be treated as regular
text.
Syntax
Following is the syntax for CDATA section:
<! [CDATA [
Characters with markup
]]>
Details of the above syntax:
CDATA Start section - CDATA begins with the nine-character
delimiter <![CDATA[

181
CDATA End section - CDATA section ends with]]> delimiter.
CData section - Characters between these two enclosures are
interpreted as characters, and not as markup. This section may contain markup
characters (<, >, and &), but they are ignored by the XML processor.
Example
Here is the example of CDATA. Here everything written inside the
CDATA section will be ignored by the parser.
<Script>
<! [CDATA [
<Message> Welcome to Tutorials Point </message>
]] >
</script >
Here <message> and </message> are treated as character data and not markup.
CDATA Rules
Following are the rules that need to be followed for XML CDATA:
CDATA cannot contain the string "]]>" anywhere in the XML document.
Nesting is not allowed in CDATA section.
White Spaces
This chapter discusses white space handling in XML documents.
Whitespaces is a collection of spaces, tabs, and newlines. These are usually
used to make a document more readable.
XML document contain two types of white spaces (a) Significant
Whitespace and (b) insignificant Whitespace. Both have been explained below
with examples.
Significant Whitespace
A significant whitespace occurs within the element which contain text
and markup mixed together. For example:
<Name>TanmayPatil</name>
and
<Name>Tanmay Patil</name>
These two elements are different because of that space
between Tanmay and Patil, and any program reading this element in an XML
file is obliged to maintain the distinction.

182
Insignificant Whitespace
Insignificant whitespace means the spaces where only element content
is allowed. For example:
<address.category="residence">
or
<address....category="...Residence">
The above two examples are same.(Here space is represented by dots
(.)). Here the space between address and category is insignificant.
A special attribute named xml:space may be attached to an element.
This indicates that white space should not be removed by applications for that
element. You can set default or preserve to this attribute as shown in the
example below:
<! ATTLIST address xml: space (default|preserve) 'preserve'>
Where:
The value default signals that applications' default white-space
processing modes are acceptable for this element;
The value preserve indicates the intent that applications preserve all the
white space.
Processing
This chapter discusses about the Processing Instructions (PIs). As
defined by the XML 1.0 Recommendation, Processing Instruction is:
"Processing instructions (PIs) allow documents to contain instructions
for applications. PIs are not part of the document's character data, but MUST be
passed through to the application.
Processing instructions (PIs) can be used to pass information to
applications so as to escapes most XML rules. PIs can appear anywhere in the
document outside of other markup. They can appear in the prolog, including the
document type definition (DTD), in textual content, or after the document.
Syntax
Following is the syntax of PI:
<? Target instructions?>
Where:
Target - identifies the application to which the instruction is directed.
Instructions - is a character that describes the information for the application
to process.

183
A PI starts with a special tag <? And ends with ?>. Processing of the
contents ends immediately after the string?> is encountered.
Example
PIs are hardly used. They are known mostly to be used to link XML
document to a stylesheet. Following is an example:
<? Xml-stylesheet href="tutorialspointstyle.css" type="text/css"?>
Here target is xml stylesheet. Href= "tutorialspointstyle.css " andtype=
" text/css" are data or instructions that the target application will use at the time
of processing of given XML document.
In this case a browser will recognize the target as saying that the XML
should be transformed before being shown; the first attribute states that the type
of the transform is XSL and the Second attribute points to its location.
Processing Instructions Rules
A PI can contain any data except the combination ?>, which would be
interpreted as the closing delimiter. Here are two examples of valid PIs:
<? Welcome to pg=10 of tutorials point?>
<? Welcome?>
Encoding
Encoding is the process of converting characters into their equivalent
binary representation. When an XML processor reads an XML document,
depending on the type of encoding it encodes the document. Hence we need to
specify the type of encoding in the XML declaration.
Types
There are mainly two types of encoding present:
UTF-8 ii ) UTF-16
UTF stands for UCS Transformation Format, and UCS itself means
Universal Character Set. The number refers to how many bits are used to
represent a simple character, either 8(one byte) or 16(two bytes). UTF-8 is the
default for documents without encoding information.
Syntax
Encoding type is included in the prolog section of the XML document.
Below is the syntax for UTF-8 encoding.
<? Xml version="1.0" encoding="UTF-8"? Standalone="no" >
Syntax for UTF-16 encoding
<? Xml version="1.0" encoding="UTF-16"? Standalone="no" >

184
Example
Following example shows the declaration of encoding:
<? Xml version="1.0" encoding="UTF-8" standalone="no”?>
<Contact-info>
<Name>Tanmay Patil</name>
<Company>Tutorials Point</company>
<Phone>(011) 123-4567</phone>
</contact-info>
In the above example encoding="UTF-8", specifies that 8-bit are used
to represent the characters. To represent 16-bit characters UTF-16 encoding
can be used.
Validation
Validation is a process by which an XML document is validated. An
XML document is said to be valid if its content matches with the elements,
attributes and other piece of an associated document type declaration (DTD)
and if the document complies with the constraints expressed in it. Validation is
dealt in two ways by the XML parser. They are:
Well-formed XML document
Valid XML document
Well-formed XML document
An XML document is said to be well-formed if it adheres to the
following rules:
NON DTD XML files must use the predefined character entities
foramp(&), apos(single quote), gt(>), lt(<), quot(double quote).
It must follow the ordering of the tag. i.e. Inner tag must be closed before the
outer tag is closed.
Opening tags must have a closing tag or have themselves self
ending.(<title>....</title> or <title/>).
Must have only one Attribute in a start tag, and has to be quoted.
amp (&), apos(single quote), gt(>), lt(<), quot(double quote)Entities other
than these must be declared.
Example
Example of well-formed XML document:
<? Xml version="1.0" encoding="UTF-8" standalone="yes”?>
<! DOCTYPE address

185
[
<! ELEMENT address (name, company, phone)>
<! ELEMENT name (#PCDATA)>
<! ELEMENT company (#PCDATA)>
<! ELEMENT phone (#PCDATA)>
]>
<Address>
<Name>Tanmay Patil</name>
<Company>Tutorials Point</company>
<Phone> (011) 123-4567</phone>
</address>
Above example is said to be well-formed as:
It defines the type of document. Here document type is element type.
It includes a root element named as address.
Every child elements are enclosed within the self explanatory tags. Here child
elements are name, company and phone.
Order of tags is maintained.
Valid XML document
If an XML document is well-formed and has an associated Document
Type Declaration (DTD), then it is said to be a valid XML document. We will
study more about DTD in the XML - DTDs.
DTDs
XML Document Type Declaration commonly known as DTD is a way
to describe precisely the XML language. DTDs check the validity of structure
and vocabulary of XML documents against the grammatical rules of the
appropriate XML language.
An XML DTD can be specified internally inside the document and it
can be kept in a separate document and then liked separately.
Syntax
Basic syntax of a DTD is as follows:
<! DOCTYPE element DTD identifier
[
declaration1
declaration2
........

186
]>
In the above syntax
A DTD starts with <! DOCTYPE delimiter.
Element tells the parser to parse the document from the root element specified.
DTD identifier is identifier for the document type definition which may be a
path to the file on the system or URL to the file on the internet. If the DTD is
pointing to external path then it’s called as external subset.
Square bracket [ ] encloses an optional list of entity declaration called internal
subset.
Internal DTD
A DTD is referred to as an internal DTD if elements are declared within
the XML files. To reference it as internal DTD, standalone attribute in XML
declaration must be set to yes; which means it will work on its own and does
not depend on external source.
Syntax
Following is the syntax of internal DTD:
<! DOCTYPE root-element [element-declarations]>
where root-element is the name of root element and element-declarations is
where you declare the elements.
Example
Following is a simple example of internal DTD:
<? Xml version="1.0" encoding="UTF-8" standalone="yes”?>
<! DOCTYPE address [
<! ELEMENT address (name, company, phone)>
<! ELEMENT name (#PCDATA)>
<! ELEMENT company (#PCDATA)>
<! ELEMENT phone (#PCDATA)>
]>
<address>
<name>Tanmay Patil</name>
<company>Tutorials Point</company>
<phone>(011) 123-4567</phone>
</address>
Let us go through the above code:

187
Starts Declaration - Begin with the XML declaration with the following
statement
<? Xml version="1.0" encoding="UTF-8" standalone="yes”?>
DTD - Immediately following the XML header is the document type
declaration, commonly referred to as the DOCTYPE:
<! DOCTYPE address [
The DOCTYPE informs the parser that a DTD is associated with this XML
document. The DOCTYPE declaration has an exclamation mark (!) at the start
of the element name.
DTD Body Following the DOCTYPE declaration is the body of the DTD. This
is where you declare elements, attributes, entities, and notations:
<! ELEMENT address (name,company,phone)>
<! ELEMENT name (#PCDATA)>
<! ELEMENT company (#PCDATA)>
<! ELEMENT phone _no (#PCDATA)>
Several elements are declared here that make up the vocabulary of the <name>
document. <! ELEMENT name (#PCDATA)> defines the element name to be
of type "#PCDATA". Here #PCDATA means parse-able text data.
End Declaration - Finally, the declaration section of the DTD is closed using a
closing bracket and a closing angle bracket (]>). This effectively ends the
definition, and the XML document immediately follows.
Rules
The document type declaration must appear at the start of the document
(preceded only by the XML header) — it is not permitted anywhere else within
the document.
Like the DOCTYPE declaration, the element declarations must start
with an exclamation mark.
The Name in the document type declaration must match the element
type of the root element.
External DTD
In external DTD elements are declared outside the XML file. They are
accessed by specifying the system attributes which may be either the
legal.dtd file or a valid URL. To reference it as external DTD, standalone
attribute in the XML declaration must be set as no, which means it depends on
the external source.

188
Syntax
Following is the syntax for external DTD:
<! DOCTYPE root-element SYSTEM "file-name">
where file-name is the file with .dtd extension.
Example
Following is a simple example of external DTD usage:
<? Xml version="1.0" encoding="UTF-8" standalone="no”?>
<! DOCTYPE address SYSTEM "address.dtd">
<address>
<name>Tanmay Patil</name>
<company>Tutorials Point</company>
<phone>(011) 123-4567</phone>
</address>
Below is the content of the DTD file address.dtd:
<! ELEMENT address (name,company,phone)>
<! ELEMENT name (#PCDATA)>
<! ELEMENT company (#PCDATA)>
<! ELEMENT phone (#PCDATA)>
Types
You can refer to an external DTD by either using system identifiers or public
identifiers.
SYSTEM IDENTIFIERS
A system identifier enables you to specify the location of an external
file containing DTD declarations. Syntax is as follows:
<! DOCTYPE name SYSTEM "address.dtd" [...]>
As you can see it contains keyword SYSTEM and a URI reference
pointing to the document’s location.
PUBLIC IDENTIFIERS
Public identifiers provide a mechanism to locate DTD resources and are
written as below:
<! DOCTYPE name PUBLIC "-//Beginning XML//DTD Address
Example//EN">
As you can see, it begins with keyword PUBLIC, followed by a
specialized identifier. Public identifiers are used to identify an entry in a

189
catalog. Public identifiers can follow any format; however, a commonly used
format is called Formal Public Identifiers, or FPIs.
Schemas
XML Schema commonly known as an XML Schema Definition (XSD),
and it is used to describe and validate the structure and the content of XML
data. XML schemas defines the elements, attributes and data type. Schema
element supports the namespaces. It is similar to what a database schema
describes the data that can be contained in a database.
Syntax
You simply have to declare the following XML Schema namespace and
assign a prefix such as xs in your XML document:
<"http://www.w3.org/2001/XMLSchema">
Example
Following is a simple example that shows how to use schema:
<? xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="contact">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="company" type="xs:string" />
<xs:element name="phone" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The basic idea behind XML Schemas is that they describe the legitimate
format that an XML document can take.
Elements
As we saw in the XML - Elements chapter, elements are the building
bloacks of XML document. An element can be defined within an XSD as
follows:
<xs:element name="x" type="y"/>

190
Definition Types
You can define XML schema elements in following ways:
(1) Simple Type - Simple type element is used only in the context of the text.
Some of predefined simple types are: xs:integer, xs:boolean, xs:string, xs:date.
For example:
<xs:element name="phone_number" type="xs:int" />
(2) Complex Type - A complex type is a container for other element
definitions. This allows you to specify which child elements an element can
contain. This allows you to provide some structure within your XML
documents. For example:
<xs:element name="Address">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="company" type="xs:string" />
<xs:element name="phone" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
As you can see in the above example, Address element consists of child
elements. This is a container for other <xs:element> definitions, allowing us to
build a simple hierarchy of elements in the resulting XML document.
(3) Global Types - With global type, you can define a single type in your
document which can be used by all other references. For example, suppose you
want to generalize the person and company for different addresses of the
company. In such cases you can define a general type as below:
<xs:element name="AddressType">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="company" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>

191
Now let us use this in type in our example as below:
<xs:element name="Address1">
<xs:complexType>
<xs:sequence>
<xs:element name="address" type="AddressType" />
<xs:element name="phone1" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Address2">
<xs:complexType>
<xs:sequence>
<xs:element name="address" type="AddressType" />
<xs:element name="phone2" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
Instead of having to define name and company twice (once for
Address1 and once for Address2) we now have a single definition. This makes
maintenance simpler, i.e. if you decide to add "Postcode" elements to your
address you only have to add them in one place.
Attributes
An attribute in XSD provides extra information within an element.
Attributes have name and type property as shown below:
<xs:attribute name="x" type="y"/>
Tree Structure
An XML document is always descriptive. Tree structure often referred
to as XML Tree and plays an important role to understand any XML documents
easily.
The tree structure contains root (parent) elements, child elements and so
on. By using tree structure you can observe which branch belongs to which root
and which sub-branch belongs to which branch. The search or parsing starts at
the root, then move down the first branch to an element, take the first branch
from there, and so on to the leaves.

192
Example
Following example demonstrates simple XML tree structure
<? Xml version="1.0"?>
<Company>
<Employee>
<FirstName>Tanmay</FirstName>
<LastName>Patil</LastName>
<ContactNo>1234567890</ContactNo>
<Email>[email protected]</Email>
<Address>
<City>Bangalore</City>
<State>Karnataka</State>
<Zip>560212</Zip>
</Address>
</Employee>
</Company>
Following tree structure represents the above XML document:

Figure 4.3: Tree Structure of the above XML document


As can be seen in the above diagram, we have a root element as
<company> and inside that we can define one more element <Employee>. And
inside employee element there are 5 branches i.e. <FirstName>, <LastName>,
<ContactNo>, <Email>, and <Address>. An inside the <Address> element we
have given three sub-branches i.e. <City> <State> <Zip>.
DOM
The Document Object Model (DOM) is the foundation of Extensible
Markup Language, or XML. XML documents have a hierarchy of

193
informational units called nodes; DOM is a way of describing those nodes and
the relationships between them.
DOM Document is a collection of nodes, or pieces of information,
organized in a hierarchy. This hierarchy allows a developer to navigate around
the tree looking for specific information. Because it is based on a hierarchy of
information, the DOM is said to be tree based.
The XML DOM, on the other hand, also provides an API that allows a
developer to add, edit, move, or remove nodes at any point on the tree in order
to create an application.
Example
The following example (sample.htm) parses an XML document
("address.xml") into an XML DOM object and then extracts some information
from it with a JavaScript:
<! DOCTYPE html>
<html>
<body>
<h1>Tutorials Point DOM example </h1>
<div>
<b>Name :< /b> <span id="name"></span><br>
<b>Company :< /b> <span id="company"></span><br>
<b>Phone :< /b> <span id="phone"></span>
</div>
<Script>
if (window. XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
Else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","/xml/address.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.getElementById("name").innerHTML=

194
xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
document.getElementById("company").innerHTML=
xmlDoc.getElementsByTagName
("company")[0].childNodes[0].nodeValue;
document.getElementById("phone").innerHTML=
xmlDoc.getElementsByTagName("phone")[0].childNodes[0].nodeValue;
</script>
</body>
</html>
Contents of address.xml are as below:
<? xml version="1.0"?>
<Contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone> (011) 123-4567</phone>
</contact-info>
Now let's keep these two files (a) sample.htm and (b) address.xml in the
same directory /xml and execute the sample.htm file by opening in any
browser. This should produce an output as shown below:
Here you can see how we extracted each of the child nodes and
displayed their values.
Namespaces
A namespace is a set of names in which all names are unique.
Namespaces are a mechanism by which element and attribute names can be
assigned to groups. The Namespace is identified by URI (Uniform Resource
Locater).
Namespace Declaration
A namespace is declared using reserved attributes. Such an attribute's
name must either be xmlns or begin xmlns:
<element xmlns: name="URI">
The namespace starts with the keyword xmlns.
Name is the namespace prefix.
And URI is the namespace identifier.

195
Example
Namespaces only affect a limited area in the document. An element
containing the declaration and all of its descendants are in the scope of the
namespace. Following is a simple example of XML Namespace:
<? Xml version="1.0" encoding="UTF-8"?>
<cont: contact xmlns:cont="www.tutorialspoint.com/profile">
<cont:name>Tanmay Patil</cont:name>
<cont:company>TutorialsPoint</cont:company>
<cont:phone>(011) 123-4567</cont:phone>
</cont:contact>
Here, we have declared the namespace prefix as cont, and the
namespace identifier (URI) as www.tutorialspoint.com/profile. This means that
element names and attribute names with the cont prefix (including the contact
element) all belong to the www.tutorialspoint.com/profile namespace.
Databases
XML Database is used to store the huge amount of information in the
XML format. As the use of the XML is increasing in every field, it is required
to have the secured place to store the XML documents. These data stored can
be queried using XQuery, serialized and exported into desired format.
XML Database Types
There are two major types of XML databases exist:
XML- enabled
Native XML (NXD)
XML- Enabled Databases
XML enabled databases are nothing but the extensions provided for the
conversion of XML document to and from. These are the relational databases,
where data are stored in table consisting of rows and columns. The table
contains set of records, records in turn consists of fields.
Native XML Databases
Native XML databases are based on the container rather than table
format. They can store large amount of XML document and data. Native XML
databases are queried by the XPath-expressions.
Native XML databases have advantages over the XML-enabled
databases. They are more capable to store, query and maintain the XML
document than XML-enabled databases.

196
Example
Following example demonstrates the XML database.
<? xml version="1.0"?>
<Contact-info>
<contact1>
<Name>Tanmay Patil</name>
<Company>TutorialsPoint</company>
<Phone>(011) 123-4567</phone>
</contact1>
<contact2>
<name>Manisha Patil</name>
<Company>TutorialsPoint</company>
<Phone>(011) 789-4567</phone>
</contact2>
</contact-info>
Here, we have created a table of contacts which holds the records of
contacts (contact1 and contact2) which in turn consists of three name, company,
and phone.
Viewers
This chapter will discuss of various methods to view an XML
document. An XML document can be viewed using a simple text editor or any
browser. Most of the major browsers support XML. XML files can be opened
in browser by just double clicking on the XML document (if it’s a local file) or
by typing the URL path in the address bar (if it’s a file on server), as in same
way as we open other files in the browser. XML files are saved with
a ".xml"extension.
Let us explore various methods by which we can view an XML file.
Following example (sample.xml) is used to view in all the sections of this
chapter.
<? Xml version="1.0"?>
<Contact-info>
<Name>Tanmay Patil</name>
<Company>TutorialsPoint</company>
<Phone>(011) 123-4567</phone>
</contact-info>

197
Text Editors
Any simple text editor such as Notepad, Text pad or Text Edit can be
used to create/view an XML document as shown below:

Firefox Browser
Open the above XML code in chrome by double clicking on the file, the
XML code displays with color coding which makes the code read easily. It
shows plus(+) or minus (-) sign at the left side in the XML element. When we
click on the minus sign(-)the code hides and by clicking on plus(+) sign the
code lines get expanded. The output that displays in Firefox is as shown below:

Chrome Browser
Open the above XML code in a chrome browser. The code gets
displayed as shown below:
Errors in XML Document
Suppose your XML code has some tags missing then a message is
displayed in the browser. Let us try to open the following XML file in chrome:
<? Xml version="1.0"?>
<Contact-info>

198
<Name>Tanmay Patil</name>
<Company>Tutorials Point</company>
<Phone> (011) 123-4567</phone>
</contact-info>
Editors
XML Editor is a markup language editor. The XML documents can be
edited or created using existing editors such as notepad, WordPad or any
simple text editor. You can also find an good professional XML editor online or
download, using which you can get many advantages as followed:
It automatically close the tags that are been opened.
The Editor will always assure that the syntax which are been written is
always right.
The XML syntax are highlighted with color code for proper readable.
It helps you to write a valid XML code.
Automatic verification of XML documents against DTD, Schemas.
Open Source XML Editors
Below we have listed some open source XML editors:
Xerlin: Xerlin is an open source XML editor for the Java 2 platform
released under an Apache style license. The project is a Java based XML
modeling application written to make creating and editing XML files easier.
CAM - Content Assembly Mechanism: CAM XML Editor tool with
XML+JSON+SQL Open-XDX sponsored by Oracle.
Parsers
XML parser is a software library or a package that provides methods (or
interfaces) for client applications to work with XML documents. It checks for
proper format of the XML document and may also validate the XML
documents. Modern day browsers have built-in XML parsers.
Following diagram shows how an XML parser interacts with XML document:

Figure 4.4: XML parser interact with XML document

199
This figure shows how a parser works. Its goal is to transform XML
into a readable code.
To ease the process of parsing, some commercial products are available
that facilitate the breakdown of XML document and yield more reliable results.
Some commonly used parsers are listed below:
MSXML (Microsoft Core XML Services): This is Microsoft’s
standard set of XML tools including a parser.
System. Xml. XmlDocument: This class is part of Microsoft’s .NET
library, which contains a number of different classes related to working with
XML.
Java built-in parser: The Java library has its own parser. The library is
designed such that you can replace the built-in parser with an external
implementation such as Xerces from Apache or Saxon.
Saxon: Saxon’s offerings contain tools for parsing, transforming, and querying
XML.
Xerces: Xerces is implemented in Java and is developed by the famous and
open source Apache Software Foundation.
4.10 Web services
A Web service is a method of communication between two electronic
devices over a network. It is a software function provided at a network address
over the Web with the service always on as in the concept of utility computing.
The W3Cdefines a Web service generally as: a software system designed to
support interoperable machine-to-machine interaction over a network.
The W3C Web Services Architecture Working Group defined a Web
Services Architecture, requiring a specific implementation of a "Web service."
In this: [a Web service] has an interface described in a machine-process able
format (specifically WSDL). Other systems interact with the Web service in a
manner prescribed by its description using SOAP (Simple Object Access
Protocol) messages, typically conveyed using HTTP with an XML serialization
in conjunction with other Web-related standards.[1]The W3C also states:
We can identify two major classes of Web services:
REST-compliant Web services, in which the primary purpose of the
service is to manipulate representations of Web resources using a uniform set
of stateless operations.
Arbitrary Web services, in which the service may expose an arbitrary
set of operations.

200
Different books and different organizations provide different definitions
to Web Services. Some of them are listed here.
A web service is any piece of software that makes itself available over
the internet and uses a standardized XML messaging system. XML is used to
encode all communications to a web service. For example, a client invokes a
web service by sending an XML message, and then waits for a corresponding
XML response. As all communication is in XML, web services are not tied to
any one operating system or programming language--Java can talk with Perl;
Windows applications can talk with UNIX applications.
Web services are self-contained, modular, distributed, dynamic
applications that can be described, published, located, or invoked over the
network to create products, processes, and supply chains. These applications
can be local, distributed, or web-based. Web services are built on top of open
standards such as TCP/IP, HTTP, Java, HTML, and XML.
Web services are XML-based information exchange systems that use
the Internet for direct application-to-application interaction. These systems can
include programs, objects, messages, or documents.
A web service is a collection of open protocols and standards used for
exchanging data between applications or systems. Software applications written
in various programming languages and running on various platforms can use
web services to exchange data over computer networks like the Internet in a
manner similar to inter-process communication on a single computer. This
interoperability (e.g., between Java and Python, or Windows and Linux
applications) is due to the use of open standards.
To summarize, a complete web service is, therefore, any service that:
Is available over the Internet or private (intranet) networks
Uses a standardized XML messaging system
Is not tied to any one operating system or programming language
Is self-describing via a common XML grammar
Is discoverable via a simple find mechanism
Components of Web Services
The basic web services platform is XML + HTTP. All the standard web
services work using the following components
SOAP (Simple Object Access Protocol)
UDDI (Universal Description, Discovery and Integration)
WSDL (Web Services Description Language)

201
NOTES
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………

202
NOTES
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………

203
UNIT – V

PHP and MySQL


In This Chapter
 Overview of PHP
 General syntactic characteristics
 Primitives, operation and exception
 output-control statement
 arrays
 functions
 pattern matching
 form handling
 files-cookies, session tracking-MySQL database system
 Database access with PHP& MySQL.
 Overview of Ajax
 The Basics of Ajax-Rails with Ajax.
5.1 Overview of PHP:
PHP (a recursive acronym for PHP: Hypertext Preprocessor) is a
scripting language used primarily to power dynamic web sites, though it can
also be used for other purposes. The common extension for PHP files is .php,
though others such as .php3 exist too, and in web servers such as Apache, it is
possible to configure the server to treat files with other extensions as PHP
scripts as well. The latest release version of the language is PHP5, though
PHP4 retains widespread use and support. PHP 6 is in development.
PHP was originally created by Rasmus Lerdof in 1995 as a set of tools
he could use to display his online CV and monitor traffic to his website, and
PHP originally stood for the first three words of his Personal Home Page Tools.
From a set of Perl scripts, PHP was ported to C, the language behind PHP to
this day. In 1997 PHP was recoded by the Israeli developers Zeev Suraski and
Andi Gutmans, who would later form Zend Technologies and release the Zend
Engine as the C core on which PHP is based.
The release dates for the main revisions of PHP are:
 PHP/FI 2 June 1997
 PHP3 June 1998
 PHP4 May 2000

204
 PHP5 July 2004
PHP is considered easy to learn in comparison to Java and many other
programming languages, though many also consider it to be less industrially
powerful. In fact, whilst PHP is incredibly popular, you will find that many
major business sites opt for other technologies and platforms. It is easy to see
why many corporations trust Java over PHP, with its foundation in a major
technology company, Sun Microsystems, versus PHP's origins as a set of
scripts for the personal use of just one programmer. However, PHP has a huge
community behind it and has become a mature web programming language in
its own right.
An example that demonstrates PHP's ease of use is the mail() function.
Using this function, sending email from within a PHP script involves a single
line of code. Another example is the file_get_contents() function, which, again
with a single line of code, can be used to retrieve the contents of a file, even a
remote, public accessible file, into a string.
The PHP processor has two modes:
1. copy (XHTML) and
2. interpret (PHP)
A PHP page must have a PHP-supported extension. Typically, a PHP
file ends with .php, although other PHP extensions such as .php4 and .phtml
also exist. However, .php is the most common extension.
To create a new PHP page
 Do one of the following:
o On the File menu, point to New, and then click PHP.
o On the File menu, click New. In the New dialog box, on
the Page tab, click General, then click PHP, and then click OK.
PHP script blocks
A PHP script block can appear anywhere in a .php page, and each page
can contain more than one PHP script block. A PHP script block must begin
with <?php and end with ?>.
The following is an example of a PHP script block:
<? Php
Echo "Hello World";
?>
To insert a PHP script block
 On the Insert menu, click PHP Script.

205
Features
 Allows you to build templates to ease site maintenance
 Serve different content to users based on their browser, IP address, date
and time, or numerous other characteristics
 Enables connections with databases such as MySQL
 Build discussion forums or Web-based email programs
 Read and process XML.
5.2 GENERAL SYNTACTIC CHARACTERISTICS:
PHP code can be specified in an XHTML document internally or
externally:
Internally: <?php
...
?>
Externally: include ("myScript.inc")
The file can have both PHP and XHTML
If the file has PHP, the PHP must be in
<?php .. ?>, even if the include is already in
<?php .. ?>
Every variable name begin with a $
Comments - three different kinds (Java and Perl)
// ...
# ...
/* ... */
 Compound statements are formed with braces
 Compound statements cannot be blocks
 Variable names are case sensitive
 However keywords and function names are not case sensitive.
5.3 PRIMITIVES, OPERATION AND EXCEPTION:
• Four scalar types: Boolean, integer, double, string
• Two compound types: array, object
• Two special types: resource and NULL.
Variables
 There are no type declarations
 The unset function sets a variable to NULL

206
 Integer & double are like those of other languages
 Strings
 Characters are single bytes
 String literals use single or double quotes
 The IsSet function is used to determine whether a variable is
NULL
 error_reporting(15); - prevents PHP from using unbound
variables
 PHP has many predefined variables, including the
environment variables of the host
 operating system
 You can get a list of the predefined variables by calling
phpinfo() in a script.
Single-quoted string literals (as in Perl)
Embedded variables are NOT interpolated
Embedded escape sequences are NOT recognized
Double-quoted string literals
 Embedded variables ARE interpolated
 If there is a variable name in a double-quoted string but you don’t
want it interpolated, it must be backslashed
 Embedded escape sequences ARE recognized
 For both single- and double-quoted literal strings, embedded
delimiters
 must be backslashed
 Boolean - values are true and false (case insensitive)
 0 and "" and "0" are false; others are true.
Arithmetic Operators and Expressions
1. Usual operators
2. If the result of integer division is not an integer, a double is returned
3. Any integer operation that results in overflow produces a double
4. The modulus operator (%) coerces its operands to integer, if
necessary
5. When a double is rounded to an integer, the rounding is always
towards zero.

207
Arithmetic functions
floor, ceil, round, abs, min, max, rand, etc.
String Operations and Functions
 The only operator is period, for catenation
 Indexing - $str.
0{3} is the fourth character.
strlen, strcmp, strpos, substr, as in C
chop – remove whitespace from the right end
trim – remove whitespace from both ends
ltrim – remove whitespace from the left end
strtolower, strtoupper
Scalar Type Conversions
 Implicit (coercions)
 String to numeric
o If the string contains an e or an E, it is converted to double;
otherwise to
 integer
o If the string does not begin with a sign or digit, zero is used.
 Explicit conversions – casts
o e.g., (int)$total or intval($total) or settype($total, "integer"
 The type of a variable can be determined with gettype or is_type
gettype($total) - it may return "unknown" is_integer($total) – a
predicate function.
5.4 OUTPUT
Output from a PHP script is HTML that is sent to the browser
HTML is sent to the browser through standard output.
• The print function is used to send data to output
• print takes string parameters, PHP coerces as necessary
• The C printf function is also available
• The first argument to printf is a string with interspersed format
codes
• A format code begins with % followed by a field width and a
type specifier

208
• Common types specifiers are s for string, d for integer and f
double
• Field width is a single integer to specify the number of
characters (minimum) used to display the value or two integers
separated by a period to indicate field width and decimal places
for double values
• printf(“x = %5d is %s\n”, $x, $size);
Displays $x as an integer and $size as a string
5.5 CONTROL STATEMENT
if, elseif, else

if (expr) { statements }
elseif (expr) { statements }
else { statements }
switch
switch (expr)
{
case condition1 : {
statements
break; }
case condition2 : {
statements
break; }
default: {
statements }
}
The switch statement executes line by line (actually, statement by
statement). When a case statement is found with a value that matches the value
of the switch expression, PHP begins to execute the statements. PHP continues
to execute the statements until the end of the switch block, or the first time it
sees a break statement. If you do not write a break statement at the end of a
case statement list, PHP will go on executing the statements of the following
case.

209
Loops
while
while (expr) { statements }
or
while (expr): statements endwhile;
In a do..while loop the first iteration is guaranteed to run (in contrary to
regular while loops):
do
{
Statements
} while (condition)
For
PHP for-loops behave like their C counterparts:
For (expr1; expr2; expr3) {statements}
The first expression (expr1) is evaluated (executed) once
unconditionally at the beginning of the loop. In the beginning of each iteration,
expr2 is evaluated. If it evaluates to TRUE, the loop continues. At the end of
each iteration, expr3 is evaluated (executed).
Each of the expressions can be empty. expr2 being empty means the
loop should be run indefinitely (PHP implicitly considers it as TRUE). You can
end the loop using a conditional break statement.
foreach
The foreach construct is like in Perl. It gives an easy way to iterate over
arrays:
for each(array_expression as $value) { statements }
or
foreach(array_expression as $key => $value) { statement }
The first form loops over the array given by array expression. On each
loop, the value of the current element is assigned to $value and the internal
array pointer is advanced.
The second form does the same thing, except that also the current
element's key will be assigned to the variable $key. When foreach first starts
executing, the internal array pointer is automatically reset to the first element.
foreach operates on a copy of the specified array. Changes are not reflected in
the original array.

210
Break
Break is used to end the execution of a for, switch, or while statement:
Break accepts an optional numeric argument which tells it how many
nested enclosing structures are to be broken out of.
$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At 5<br>\n";
break 1; /* Exit only the switch. */
case 10:
echo "At 10; quitting<br>\n";
break 2; /* Exit the switch and the while. */
default:
break;
}
}
Continue
The continue statement is used to skip the rest of the current loop and
continue execution at the beginning of the next iteration.
while (list ($key, $value) = each ($arr)) {
if ($key % 2) { // skip odd members
continue;
}
do_something_odd ($value);
}
continue also accepts an optional numeric argument which tells it how
many levels of enclosing loops it should skip.
declare and ticks
Declare-Ticks can be used for debugging, implementing simple
multitasking, back grounded I/O and many other tasks.
The declare construct is used to set execution directives for a block of
code:
declare (directive) { statements }

211
Currently only one directive is recognized: ticks=N
A tick is an event that occurs for every N low-level statements executed
by the parser within the declare block.
5.6 ARRAYS – FUNCTIONS
An array is a variable that contains multiple values which can be strings,
numbers or other arrays.
To create an array:
1) $fruit = array (“apples”, “pears”, “oranges”, “plums”)
2) $fruit = array(); // initialize array use round brackets
$fruit[0] = “apples”; // assign key to each array element
$fruit[1] = “pears”;
$fruit[2]= “oranges”;
$fruit[3]= “plums”;
3) Associative Array – you associate a string or other value – you don’t
use serial
numbers
$provincialcapital[“Edmonton”];
$provincialcapital[“Toronto”];
$provincialcapital[“Halifax”];
or
$soups = array(
“Monday” => “Clam Chowder”,
“Tuesday” =>”White Chicken”,
“Wednesday => “Vegetarian”
);
If you try to output the array elements by using the echo or print
statement:
<?php
print “$soups <br />\n”;
?>
ADDING MORE ELEMENTS TO AN ARRAY
COUNT() function
If you want to see how many elements are in an array you can use the
count() function like so:
<?php

212
$soups = array(
"Monday" => "Clam Chowder",
"Tuesday" => "White Chicken",
"Wednesday" => "Vegetarian",
);
print "$soups <br>\n";
$howmany = count($soups);
print "$howmany";
?>
it will display 3 in this case.
To add more elements to the array:
$soups[“Thursday”] = “Chicken noodle”;
$soups[“Friday”] = “Tomato”;
$soups[“Saturday”] = “Cream of Broccoli”;
$nowhomany = count($soups);
print "$nowhowmany";
MERGING ARRAYS
array_merge() function
The array_merge() function is new to PHP4 – it allows you combine
elements of different arrays
into one array.
<?php
$fruits = array("apples", "oranges", "pears");
$vegetables = array("potatoes", "celery", "carrots");
$newarray = array_merge($fruits, $vegetables);
$howmany = count($newarray);
print "$howmany"; // will output 6 to the screen
?>
Note the order you merge the arrays in will determine the order they
appear i.e.
array_merge($fruits, $vegetables) will be different from
array_merge($vegetables, $fruits).

213
ACCESSING ARRAY ELEMENTS
To access individual array elements you refer to them by their index
number which usually starts at 0 but you can assign the array to start at any
number. With an associative array you refer to the entire element e.g. $soups
[“Monday] - not the use of the square brackets.
e.g in the previous example to view the first vegetable in the array
add the code:
Print “$vegetables [0]”; // this will print to the screen potatoes
Print “$vegetables [1]” ; // this will print to the screen celery
You could also assign the array element to a separate variable e.g.
$veg = $vegetables [1];
Print “$veg”; // will output celery to the screen
One of the limitations of arrays is that in order to refer to a specific
element you must know the keys to which the specific element refers to and in
the case of associate arrays $soups[1] will not point to nothing since its value is
a string, i.e. $soups[“Monday”]
SORTING ARRAYS
Php provides a variety of functions to sort arrays alphabetically or
numerically.
To sort the values in an array without regard to their keys use: sort(0
and rsort(), the latter being
reverse sort.
sort($array)
rsort($array)
To sort the values while keeping the correlation between the value and the key
use:
assort($array)
arsort($array) // reverse sort
To sort by the keys while maintaining the correlation between the key and its
value:
ksort($array)
krsort($array)
To randomize the order of the array you can use:
Shuffle($array)
<?php

214
$grades = array();
$grades["Richard"] = 95;
$grades ["Sherwood"] = 82;
$grades ["Toni"] = 98;
$grades ["Fanz"] = 87;
$grades ["Melisa"]= 75;
// use each since it is an associative array
for ($x=0; $x <count($grades); $x++)
{
$Line = each($grades);
print "$Line[key] $Line[value] $grades[$x] <br>\n";
}
?>
Transforming Between Strings and Arrays Implode() and Explode()
FUNCTIONS
You can convert and array into a string and vice versa. You might want
to turn a string into an array to read information from a text file or database, or
you might want to change an array into a string in order to store the data in a
text file or database. Another possible use is that you might want to convert a
comma-delimited text field e.g. keyword search area of a form into its separate
parts.
Explode() syntax
$array = explode($separator, $string);
The separator refers to whatever character(s) define where one array
element ends and another
begins. Normally this is a comma or blank space:
Convert array to string:
$array = explode(“,”, $string);
or
$array = explode(“ ”, $string);
Convert string to an array Implode() syntax
$string = implode($glue, $array); // glue is the separator you want to
add
$string = implode(“,”, $array);
$string = implode(“ “, $array);

215
WORKING WITH ARRAYS
To change an element in an array
<?php
$fruits = array(“apple”, “banana”, “orange”, “grape”)
$fruits[0] = “apricot”; // to change an element type name of array[]
include number
$fruits[2] = “strawberry”;
?>
If you specify a number greater than the largest index number, PHP will
not create elements to fill the gap between the index numbers.
If a new element is added to an array that does not exist, a new array
will be created. However, It is best to create the array first.
You can create an empty array then later add elements to that array.
This is useful if you want to filter array elements or dynamically add elements
using data obtained from a form or database.
FUNCTIONS
PHP functions are similar to other programming languages. A function
is a piece of code which takes one more input in the form of parameter and
does some processing and returns a value.
You already have seen many functions like fopen() and fread() etc.
They are built-in functions but PHP gives you option to create your own
functions as well.
There are two parts which should be clear to you:
 Creating a PHP Function
 Calling a PHP Function
In fact you hardly need to create your own PHP function because there
are already more than 1000 of built-in library functions created for
different area and you just need to call them according to your
requirement.
Creating PHP Function
It’s very easy to create your own PHP function. Suppose you want to
create a PHP function which will simply write a simple message on your
browser when you will call it. Following example creates a function called
write Message () and then calls it just after creating it.

216
Note that while creating a function its name should start with keyword
function and all the PHP code should be put inside {and} braces as shown in
the following example below:
<Html>
<Head>
<Title>Writing PHP Function</title>
</head>
<Body>
<?php
/* Defining a PHP Function */
function writeMessage()
{
echo "You are really a nice person, Have a nice time!";
}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>
This will display following result:
PHP Functions with Parameters
PHP gives you option to pass your parameters inside a function. You
can pass as many as parameters your like. These parameters work like
variables inside your function. Following example takes two integer
parameters and add them together and then print them.
<Html>
<Head>
<Title>Writing PHP Function with Parameters</title>
</head>
<Body>
<? Php
Function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
Echo "Sum of the two numbers is : $sum";

217
}
addFunction(10, 20);
?>
</body>
</html>
This will display following result:
Sum of the two numbers is : 30
Passing Arguments by Reference
It is possible to pass arguments to functions by reference. This means
that a reference to the variable is manipulated by the function rather than a
copy of the variable's value.
Any changes made to an argument in these cases will change the value
of the original variable. You can pass an argument by reference by adding an
ampersand to the variable name in either the function call or the function
definition.
Following example depicts both the cases.
<Html>
<Head>
<Title>Passing Argument by Reference</title>
</head>
<Body>
<? Php
Function addFive($num)
{
$num += 5;
}
Function addSix(&$num)
{
$num += 6;
}
$orignum = 10;
addFive( $orignum );
Echo "Original Value is $orignum<br />";
addSix( $orignum );
Echo "Original Value is $orignum<br />";

218
?>
</body>
</html>
This will display following result:
Original Value is 10
Original Value is 16
PHP Functions returning value
A function can return a value using the return statement in conjunction
with a value or object. Return stops the execution of the function and sends the
value back to the calling code.
You can return more than one value from a function using return
array(1,2,3,4).
Following example takes two integer parameters and add them together
and then returns their sum to the calling program. Note that returnkeyword is
used to return a value from a function.
<Html>
<Head>
<Title>Writing PHP Function which returns value</title>
</head>
<Body>
<? Php
Function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
Return $sum;
}
$return_value = addFunction(10, 20);
Echo "Returned value from the function: $return_value";
?>
</body>
</html>
This will display following result:
Returned value from the function: 30

219
Setting Default Values for Function Parameters
You can set a parameter to have a default value if the function's caller
doesn't pass it.
Following function prints NULL in case use does not pass any value to
this function.
<Html>
<Head>
<Title>Writing PHP Function which returns value</title>
</head>
<Body>
<? Php
Function printMe($param = NULL)
{
Print $param;
}
printMe("This is test");
printMe();
?>
</body>
</html>
Dynamic Function Calls
It is possible to assign function names as strings to variables and then
treat these variables exactly as you would the function name itself. Following
example depicts this behavior.
<Html>
<Head>
<Title>Dynamic Function Calls</title>
</head>
<Body>
<? Php
Function sayHello()
{
Echo "Hello<br />";
}

220
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>
General Characteristics
 Functions need not be defined before they are called
 Function overloading is not supported
 If you try to redefine a function, it is an error
 Functions can have a variable number of parameters
 Default parameter values are supported
 Function definitions can be nested
 Function names are NOT case sensitive
 The return function is used to return a value;
 If there is no return, there is no returned value.
Parameters
1. If the caller sends too many actual parameters, the subprogram
ignores the extra ones
2. If the caller does not send enough parameters, the unmatched
formal parameters are unbound
3. The default parameter passing method is pass by value (one-way
communication)
4. To specify pass-by-reference, prepend an ampersand to the
formal parameter
Function set_max(&$max, $first, $second) {
If ($first >= $second)
$max = $first;
Else
$max = $second;
}
5. If the function does not specify its parameter to be pass by
reference, you can prepend an ampersand to the actual parameter
and still get pass-by reference semantics.

221
Return Values
1. Any type may be returned, including objects an arrays, using the
return.
2. If a function returns a reference, the name of the function must have
a prepended
Ampersand
Function &newArray($x) { … }
The Scope of Variables
1. An undeclared variable in a function has the scope of the function
2. To access a nonlocal variable, it must be declared to be global, as in
Global $sum;
The Lifetime of Variables
Normally, the lifetime of a variable in a function is from its first
appearance to the end of the function’s execution
Static $sum = 0; # $sum is static
5.7 PATTERN MATCHING
• PHP provides both POSIX regular expressions and Perl regular
expressions
• These are generally the same but differ in certain details
• The preg_match function matches a pattern, given as a string,
with a string
• The preg_split function splits a string into an array of strings
based on a pattern describing the separators
• The word_table.php example illustrates pattern matching in
PHP.
PHP has two kinds:
i. POSIX
ii. Perl-compatible
Preg_match(regex, str [,array])
The optional array is where to put the matches.
5.8 FORM HANDLING – Files
Forms could be handled by the same document that creates the form,
but that may be confusing.
PHP particulars:

222
 It does not matter whether GET or POST method is used
to transmit the form data
 PHP builds an array of the form values ($_GET for the
GET method and $_POST for the POST method –
subscripts are the widget names).
FILES:
PHP can:
 Deal with any files on the server
 Deal with any files on the Internet, using either http or ftp
 Instead of file handles, PHP associates a variable with a file,
called the file variable (for program reference)
 A file has a file pointer (where to read or write)
$fptr = fopen(filename, use_indicator)
Use indicators:
r read only, from the beginning
r+ read and write, from the beginning
w write only, from the beginning
(also creates the file, if necessary)
w+ read and write, from the beginning
(also creates the file, if necessary)
a write only, at the end, if it exists
(creates the file, if necessary)
a+ read and write, read at the beginning, write at the end.
- Because fopen could fail, use it with die
Use file_exists(filename) to determine whether file exists before trying
to open it.
Reading files
1. Read all or part of the file into a string variable
$str = fread(file_var, #bytes)
- To read the whole file, use
filesize(file_name)
as the second parameter
2. Read all of the lines of the file into an array
@file_lines = file(file_name)

223
- Need not open or close the file
3. Read one line from the file
$line = fgets(file_var, #bytes)
- Reads characters until eoln, eof, or #bytes-
characters have been read
4. Read one character at a time
$ch = fgetc(file_var)
Writing File:
 Control reading lines or characters with eof
Detection using feof (TRUE for eof; FALSE
Otherwise)
While (!feof($file_var)) {
$ch = fgetc($file_var);
}
Writing to files
$bytes_written = fwrite(file_var, string)
- fwrite returns the number of bytes it wrote
- Files can be locked (to avoid interference from
Concurrent accesses) with flock.
Locking Files:
The flock function will lock a named file
The function takes a second parameter giving the mode of the lock
• 1 specifies others can read
• 2 specifies no other access is allowed
• 3 remove the lock.
5.9 COOKIES, SESSION TRACKING
Cookies are text files stored on the client computer and they are kept of
use tracking purpose. PHP transparently supports HTTP cookies.
There are three steps involved in identifying returning users:
 Server script sends a set of cookies to the browser. For example name,
age, or identification number etc.
 Browser stores this information on local machine for future use.

224
 When next time browser sends any request to web server then it sends
those cookies information to the server and server uses that
information to identify the user.
The Anatomy of a Cookie
Cookies are usually set in an HTTP header (although JavaScript can
also set a cookie directly on a browser). A PHP script that sets a cookie might
send headers that look something like this:
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
Path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header contains a name value pair, a
GMT date, a path and a domain. The name and value will be URL encoded.
The expires field is an instruction to the browser to "forget" the cookie after the
given time and date.
If the browser is configured to store cookies, it will then keep this
information until the expiry date. If the user points the browser at any page
that matches the path and domain of the cookie, it will resend the cookie to the
server. The browser's headers might look something like this:
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
A PHP script will then have access to the cookie in the environmental
variables $_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie
names and values. Above cookie can be accessed using
$HTTP_COOKIE_VARS["name"].

225
Setting Cookies with PHP
PHP provided setcookie() function to set a cookie. This function
requires upto six arguments and should be called before <html> tag. For each
cookie this function has to be called separately.
setcookie(name, value, expire, path, domain, security);
Here is the detail of all the arguments:
 Name - This sets the name of the cookie and is stored in an
environment variable called HTTP_COOKIE_VARS. This variable is
used while accessing cookies.
 Value -This sets the value of the named variable and is the content that
you actually want to store.
 Expiry - This specify a future time in seconds since 00:00:00 GMT on
1st Jan 1970. After this time cookie will become inaccessible. If this
parameter is not set then cookie will automatically expire when the
Web Browser is closed.
 Path -This specifies the directories for which the cookie is valid. A
single forward slash character permits the cookie to be valid for all
directories.
 Domain - This can be used to specify the domain name in very large
domains and must contain at least two periods to be valid. All cookies
are only valid for the host and domain which created them.
 Security - This can be set to 1 to specify that the cookie should only be
sent by secure transmission using HTTPS otherwise set to 0 which
mean cookie can be sent by regular HTTP.
Following example will create two cookies name and age these
cookies will be expired after one hour.
<? Php
setcookie("name", "John Watkin", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<Html>
<Head>
<Title>Setting Cookies with PHP</title>
</head>
<Body>
<? Php echo "Set Cookies"?>

226
</body>
</html>
Accessing Cookies with PHP
PHP provides many ways to access cookies. Simplest way is to use
either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example
will access all the cookies set in above example.
<Html>
<Head>
<Title>Accessing Cookies with PHP</title>
</head>
<Body>
<? Php
Echo $_COOKIE ["name"]. "<br />";
/* is equivalent to */
Echo $HTTP_COOKIE_VARS ["name"]. "<br />";
Echo $_COOKIE ["age"] . "<br />";
/* is equivalent to */
Echo $HTTP_COOKIE_VARS ["name"] . "<br />";
?>
</body>
</html>
You can use isset() function to check if a cookie is set or not.
<Html>
<Head>
<Title>Accessing Cookies with PHP</title>
</head>
<Body>
<? Php
If ( isset($_COOKIE["name"]))
Echo "Welcome”. $_COOKIE ["name"] . "<br />";
Else
Echo "Sorry... Not recognized" . "<br />";
?>
</body>

227
</html>
Deleting Cookie with PHP
Officially, to delete a cookie you should call setcookie() with the name
argument only but this does not always work well, however, and should not be
relied on.
It is safest to set the cookie with a date that has already expired:
<? Php
Set cookie ( "name", "", time () - 60, "/","", 0);
Set cookie ( "age", "", time () - 60, "/","", 0);
?>
<Html>
<Head>
<Title>Deleting Cookies with PHP</title>
</head>
<Body>
<? Php echo "Deleted Cookies”?>
</body>
</html>
SESSION TRACKING
An alternative way to make data accessible across the various pages of
an entire website is to use a PHP Session.
A session creates a file in a temporary directory on the server where
registered session variables and their values are stored. This data will be
available to all pages on the site during that visit.
The location of the temporary file is determined by a setting in
the php.inifile called session.save_path. Bore using any session variable
make sure you have setup this path.
When a session is started following things happen:
 PHP first creates a unique identifier for that particular session which is
a random string of 32 hexadecimal numbers such as
3c7foj34c3jj973hjkop2fc937e3443.
 A cookie called PHPSESSID is automatically sent to the user's
computer to store unique session identification string.
 A file is automatically created on the server in the designated
temporary directory and bears the name of the unique identifier
prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443.

228
When a PHP script wants to retrieve the value from a session variable,
PHP automatically gets the unique session identifier string from the
PHPSESSID cookie and then looks in its temporary directory for the file
bearing that name and a validation can be done by comparing both values.
A session ends when the user loses the browser or after leaving the site,
the server will terminate the session after a predetermined period of time,
commonly 30 minutes duration.
Starting a PHP Session
A PHP session is easily started by making a call to
the session_start()function. These functions first checks if a session is already
started and if none is started then it starts one. It is recommended to put the call
tosession_start() at the beginning of the page.
Session variables are stored in associative array called $_SESSION [].
These variables can be accessed during lifetime of a session.
The following example starts a session then registers a variable called
counter that is incremented each time the page is visited during the session.
Make use of isset() function to check if session variable is already set or
not.
Put this code in a test.php file and load this file many times to see the
result:
<? Php
session_start();
If (isset ($_SESSION ['counter'] ) )
{
$_SESSION ['counter'] += 1;
}
Else
{
$_SESSION ['counter'] = 1;
}
$msg = "You have visited this page ". $_SESSION ['counter'];
$msg. = "in this session.";
?>
<Html>
<Head>
<Title>Setting up a PHP session</title>

229
</head>
<Body>
<? Php echo ($msg) ;?>
</body>
</html>
Destroying a PHP Session
A PHP session can be destroyed by session_destroy() function. This
function does not need any argument and a single call can destroy all the
session variables. If you want to destroy a single session variable then you can
use unset() function to unset a session variable.
Here is the example to unset a single variable:
<? Php
Unset ($_SESSION ['counter']);
?>
Here is the call which will destroy all the session variables:
<? Php
session_destroy();
?>
Turning on Auto Session
You don't need to call start_session() function to start a session when a
user visits your site if you can set session.auto_start variable to 1
in php.ini file.
Sessions without cookies
There may be a case when a user does not allow to store cookies on
their machine. So there is another method to send session ID to the browser.
Alternatively, you can use the constant SID which is defined if the
session started. If the client did not send an appropriate session cookie, it has
the form session_name=session_id
Otherwise, it expands to an empty string. Thus, you can embed it
unconditionally into URLs.
The following example demonstrates how to register a variable, and
how to link correctly to another page using SID.
<? Php
session_start();
if (isset($_SESSION['counter'])) {

230
$_SESSION ['counter'] = 1;
} else {
$_SESSION ['counter'] ++;
}
?>
$msg = "You have visited this page ". $_SESSION ['counter'];
$msg. = "in this session.”
Echo ($msg);
<p>
To continue click following link <br />
<a href="nextpage.php?<?php echo htmlspecialchars(SID); >">
</p>
The htmlspecialchars() may be used when printing the SID in order to
prevent XSS related attacks.
5.10 MYSQL DATABASE SYSTEM
What is MySQL?
Open source database system
Like most modern Database Management Systems is based on the
relational model,RDBMS.
Free Run on Linux, Windows, Netware, AIX, and so on.
Easily accessible through programming languages like PHP.
Why MySQL?
Open source database
Consistent fast performance & high reliability
Ease of use
High Availability
Comprehensive Application Development
Management Ease
Lowest Total Cost of Ownership
Where you can get it?
You can download at mysql official website, mysql.com
You can get mysql that packaged with php like in AppServ
• List databases available
– Mysql_list_tables()

231
•Create query string
– $query = ‘SQL formatted string’
– $query = ‘SELECT * FROM table’
• Submit query to database for processing
– $result = mysql_query($query);
– For UPDATE, DELETE, DROP, etc, returns TRUE or FALSE
– For SELECT, SHOW, DESCRIBE or EXPLAIN, $result is an
identifier for the results, and does not contain the results
themselves
• $result is called a “resource” in this case
• A result of FALSE indicates an error
• If there is an error
– mysql_error() returns error string from last MySQL call
5.11 DATABASE ACCESS WITH PHP& MYSQL
MySQL Server
Available for all modern server OS. (Requires C++ and support for
multi‐th di ) threading.)
Working with server—3 methods:
MySQL Monitor executed from terminal window on server (command
line tool, part of server install)
MySQL Monitor Monitor executed executed from different different
server, server, connecting to target server. (Target server account must permit
remote log in.)
MySQL GUI Tools—MySQL Administrator, MySQL Query Browser,
and MySQL Migration Toolkit.
5.12. OVERVIEW OF AJAX:
What is AJAX?
AJAX = Asynchronous JavaScript and XML.
AJAX is a technique for creating fast and dynamic web pages.
AJAX allows web pages to be updated asynchronously by exchanging
small amounts of data with the server behind the scenes. This means
that it is possible to update parts of a web page, without reloading the
whole page.
Classic web pages, (which do not use AJAX) must reload the entire
page if the content should change.

232
Examples of applications using AJAX: Google Maps, Gmail, YouTube,
and Face book tab
How AJAX Works

Figure 5.1: AJAX Works


AJAX
Ajax is a group of interrelated Web development techniques used on
the client-side to create asynchronous Web applications. With Ajax, web
applications can send data to and retrieve from a server asynchronously (in the
background) without interfering with the display and behavior of the existing
page. Data can be retrieved using the XMLHttpRequest object. Despite the
name, the use of XML is not required (JSON is often used in the AJAJ variant),
and the requests do not need to be asynchronous.
Ajax is not a single technology, but a group of technologies. HTML and
CSS can be used in combination to mark up and style information. The DOM is
accessed with JavaScript to dynamically display – and allow the user to interact
with – the information presented. JavaScript and the XMLHttpRequest object
provide a method for exchanging data asynchronously between browser and
server to avoid full page reloads.
Overview of Ajax
Ajax refers to JavaScript and XML, technologies that are widely used
for creating dynamic and asynchronous web content. While Ajax is not limited
to JavaScript and XML technologies, more often than not they are used
together by web applications. The focus of this tutorial is on using JavaScript
based Ajax functionality in Java Server Faces web applications.
JavaScript is a dynamic scripting language for web applications. It
allows users to add enhanced functionality to user interfaces and allows web

233
pages to interact with clients asynchronously. JavaScript runs mainly on the
client side (as in a browser) and thereby reduces server access by clients.
When a JavaScript function sends an asynchronous request from the
client to the server, the server sends back a response that is used to update the
page’s Document Object Model (DOM). This response is often in the format of
an XML document. The term Ajax refers to this interaction between the client
and server.
The server response need not be in XML only; it can also be in other
formats, such as JSON. This tutorial does not focus on the response formats.
Ajax enables asynchronous and partial updating of web applications.
Such functionality allows for highly responsive web pages that are rendered in
near real time. Ajax-based web applications can access server and process
information and can also retrieve data without interfering with the display and
rendering of the current web page on a client (such as a browser).
Some of the advantages of using Ajax are as follows:
 Form data validation in real time, eliminating the need to submit the form
for verification
 Enhanced functionality for web pages, such as user name and password
prompts
 Partial update of the web content, avoiding complete page reloads
Technologies
The term Ajax has come to represent a broad group of Web technologies
that can be used to implement a Web application that communicates with a
server in the background, without interfering with the current state of the page.
In the article that coined the term Ajax,[3] Jesse James Garrett explained that the
following technologies are incorporated:
 HTML (or XHTML) and CSS for presentation
 The Document Object Model (DOM) for dynamic display of and
interaction with data
 XML for the interchange of data, and XSLT for its manipulation
 The XMLHttpRequest object for asynchronous communication
 JavaScript to bring these technologies together
Since then, however, there have been a number of developments in the
technologies used in an Ajax application, and the definition of the term Ajax.
XML is not required for data interchange and, therefore, XSLT is not required
for the manipulation of data. JavaScript Object Notation (JSON) is often used

234
as an alternative format for data interchange, although other formats such as
preformatted HTML or plain text can also be used.
Asynchronous HTML and HTTP (AHAH) involves using
XMLHttpRequest to retrieve (X) HTML fragments, which are then inserted
directly into the Web page.
Drawbacks
 In pre-HTML5 browsers, pages dynamically created using successive Ajax
requests did not automatically register themselves with the browser's
history engine, so clicking the browser's "back" button may not have
returned the browser to an earlier state of the Ajax-enabled page, but may
have instead returned to the last full page visited before it. Such
behavior — navigating between pages instead of navigating between page
states — may be desirable, but if fine-grained tracking of page state is
required, then a pre-HTML5 workaround was to use invisible iframes to
trigger changes in the browser's history. A workaround implemented by
Ajax techniques is to change the URL fragment identifier (the part of a
URL after the "#") when an Ajax-enabled page is accessed and monitor it
for changes.[12][13]HTML5 provides an extensive API standard for working
with the browser's history engine.[14]
 Dynamic Web page updates also make it difficult to bookmark and return
to a particular state of the application. Solutions to this problem exist, many
of which again use the URL fragment identifier.[12][13] The solution
provided by HTML5 for the above problem also applies for this.[14]
 Depending on the nature of the Ajax application, dynamic page updates
may interfere disruptively with user interactions, especially if working on
an unstable Internet connection. For instance, editing a search field may
trigger a query to the server for search completions, but the user may not
know that a search completion popup is forthcoming, and if the internet
connection is slow, the popup list may show up at an inconvenient time,
when the user has already proceeded to do something else.
 Excluding Google,[15] most major Web crawlers do not execute JavaScript
code,[16] so in order to be indexed by search engines, a Web application
must provide an alternative means of accessing the content that would
normally be retrieved with Ajax. It has been suggested that a headless
browser may be used to index content provided by Ajax-enabled
websites.[17]
 Any user whose browser does not support JavaScript or XMLHttpRequest,
or simply has this functionality disabled, will not be able to properly use
pages which depend on Ajax. Devices such as smart phones and PDAs may

235
not have support for the required technologies, though this is becoming less
of a problem. The only way to let the user carry out functionality is to fall
back to non-JavaScript methods. This can be achieved by making sure links
and forms can be resolved properly and not relying solely on Ajax.[18]
 Similarly, some Web applications that use Ajax are built in a way that
cannot be read by screen-reading technologies, such as JAWS. The WAI-
ARIA standards provide a way to provide hints in such a case.[19]
 Screen readers that are able to use Ajax may still not be able to properly
read the dynamically generated content.[20]
 The same origin policy prevents some Ajax techniques from being used
across domains,[8] although the W3C has a draft of the XMLHttpRequest
object that would enable this functionality.[21] Methods exist to sidestep this
security feature by using a special Cross Domain Communications channel
embedded as an iframes within a page,[22] or by the use of JSONP.
 The asynchronous callback-style of programming required can lead to
complex code that is hard to maintain, to debug [23] and to test.[24]
Advantages of AJAX
 Reduce the traffic travels between the client and the server.
 Response time is faster so increases performance and speed.
 You can use JSON (JavaScript Object Notation) which is alternative
to XML. JSON is key value pair and works like an array.
 You can use Firefox browser with an add-on called as Firebug to debug
all Ajax calls.
 Ready Open source JavaScript libraries available for use – JQuery,
Prototype, Scriptaculous, etc..
 AJAX communicates over HTTP Protocol.
Disadvantages of AJAX
 It can increase design and development time
 More complex than building classic web application
 Security is less in AJAX application as all files are downloaded at client
side.
 Search Engine like Google cannot index AJAX pages.
 JavaScript disabled browsers cannot use the application.
 Due to security constraints, you can only use it to access information
from the host that served the initial page. If you need to display
information from another server, it is not possible within the AJAX.

236
Using Ajax Functionality with Java Server Faces Technology
Ajax functionality can be added to a JavaServer Faces application in
one of the following ways:
 Adding the required JavaScript code to an application
 Using the built-in Ajax resource library
In earlier releases of the Java EE platform, Java Server Faces
applications provided Ajax functionality by adding the necessary JavaScript to
the web page. In the Java EE 6 platform, standard Ajax support is provided by a
built-in JavaScript resource library.
With the support of this JavaScript resource library, Java Server Faces
standard UI components, such as buttons, labels, or text fields, can be enabled
for Ajax functionality. You can also load this resource library and use its
methods directly from within the managed bean code. The next sections of the
tutorial describe the use of the built-in Ajax resource library.
In addition, because the Java Server Faces technology component
model can be extended, custom components can be created with Ajax
functionality.
An Ajax version of the guess number application, ajaxguessnumber, is
available in the example repository. See the ajaxguessnumber Example
Application for more information.
Using Ajax with Face lets
As mentioned in the previous section, JavaServer Faces technology
supports Ajax by using a built-in JavaScript resource library that is provided as
part of the JavaServer Faces core libraries. This built-in Ajax resource can be
used in JavaServer Faces web applications in one of the following ways:
 By using the f: Ajax tag along with another standard component in a
Facelets application. This method adds Ajax functionality to any UI
component without additional coding and configuration.
 By using the JavaScript API method jsf.ajax.request () directly within the
Face lets application. This method provides direct access to Ajax methods,
and allows customized control of component behavior.
Using the f: Ajax Tag
The f: Ajax tag is a JavaServer Faces core tag that provides Ajax
functionality to any regular UI component when used in conjunction with that
component. In the following example, Ajax behavior is added to an input
component by including the f:ajax core tag:
<h: inputText value="# {bean.message}">

237
<f: Ajax />
</h: inputText>
In this example, although Ajax is enabled, the other attributes of
the f:ajax tag are not defined. If an event is not defined, the default action for
the component is performed. For the inputTextcomponent, when
no event attribute is specified, the default event is valueChange. Table 5.1 lists
the attributes of the f:ajax tag and their default actions.
Table 5.1: Attributes of the f:ajax Tag

Name Type Description

disabled javax.el.Value A Boolean value that identifies the tag status. A


Expressionthat value of true indicates that the Ajax behavior
evaluates to should not be rendered. A value of false indicates
a Boolean that the Ajax behavior should be rendered. The
default value is false.

event javax.el.Value A String that identifies the type of event to which


Expressionthat the Ajax action will apply. If specified, it must be
evaluates to one of the events supported by the component. If
a String not specified, the default event (the event that
triggers the Ajax request) is determined for the
component. The default event is action for
javax.faces.component.ActionSource components
and value Change for
javax.faces.component.EditableValueHoldercomp
onents.

execute javax.el.Value A Collection that identifies a list of components to


Expression that be executed on the server. If a literal is specified,
evaluates to it must be a space-delimited String of component
an Object identifiers and/or one of the keywords. If a Value
Expression is specified, it must refer to a property
that returns a Collection of String objects. If not
specified, the default value is @this.

immedia javax.el.Value A Boolean value that indicates whether inputs are


te Expression that to be processed early in the lifecycle. If true,
evaluates to behavior events generated from this behavior are

238
a Boolean broadcast during the Apply Request Values phase.
Otherwise, the events will be broadcast during the
Invoke Applications phase.

listener javax.el. The name of the listener method that is called


Method when a javax.faces.event.AjaxBehaviorEvent has
Expression been broadcast for the listener.

onevent javax.el. Value The name of the JavaScript function that handles
Expression that UI events.
evaluates to
a String

onerror javax.el.Value The name of the JavaScript function that handles


Expressionthat errors.
evaluates to
a String

render javax.el.Value A Collection that identifies a list of components to


Expressionthat be rendered on the client. If a literal is specified, it
evaluates to must be a space-delimited String of component
an Object identifiers and/or one of the keywords. If
aValueExpression is specified, it must refer to a
property that returns a Collection of Stringobjects.
If not specified, the default value is @none.

The keywords listed in Table 1can be used with the execute and render
attributes of the f:ajaxtag.
Table 1 Execute and Render Keywords

Keyword Description

@all All component identifiers

@form The form that encloses the component

@none No component identifiers

@this The element that triggered the request

239
Sending an Ajax Request
To activate Ajax functionality, the web application must create an Ajax
request and send it to the server. The server then processes the request.
The application uses the attributes of the f:ajax tag listed in the
following sections explain the process of creating and sending an Ajax request
using some of these attributes.
Using the event Attribute
The event attribute defines the event that triggers the Ajax action. Some
of the possible values for this attribute are click, key up, mouse over, focus,
and blur.
If not specified, a default event based on the parent component will be
applied. The default event is action for javaxfaces.component.ActionSource
components such as a command Button, and value Change for
javax.faces.component.EditableValueHolder components such as inputText. In
the following example, an Ajax tag is associated with the button component,
and the event that triggers the Ajax action is a mouse click:
<h: commandButton id="submit" value="Submit">
<f: Ajax event="click" />
</h: commandButton>
<h: outputText id="result" value="# {userNumberBean.response}" />
For a command button, the default event is click, so that you do not actually
need to specify event="click" to obtain the desired behavior.
Using the execute Attribute
The execute attribute defines the component or components to be
executed on the server. The component is identified by its id attribute. You can
specify more than one executable component. If more than one component is to
be executed, specify a space-delimited list of components.
When a component is executed, it participates in all phases of the
request processing lifecycle except the Render Response phase.
The execute attribute can also be a keyword, such as @all, @none,
@this, or @form. The default value is @this, which refers to the component
within which the f:ajax tag is nested.
The following code specifies that the h:inputText component with
the id value of userNo should be executed when the button is clicked:
<h: inputText id="userNo"
Title="Type a number from 0 to 10:"
Value="# {userNumberBean.userNumber}">

240
...
</h: inputText>
<h: commandButton id="submit" value="Submit">
<f: Ajax event="click" execute="userNo" />
</h: commandButton>
Using the immediate Attribute
The immediate attribute indicates whether user inputs are to be
processed early in the application lifecycle or later. If the attribute is set to true,
events generated from this component are broadcast during the Apply Request
Values phase. Otherwise, the events will be broadcast during the Invoke
Applications phase. If not defined, the default value of this attribute is false.
Using the listener Attribute
The listener attribute refers to a method expression that is executed on
the server side in response to an Ajax action on the client. The listener’s
javax.faces.event. AjaxBehaviorListener. ProcessAjaxBehavior method is
called once during the Invoke Application phase of the lifecycle. In the
following example, a listener attribute is defined by an f:ajax tag, which refers
to a method from the bean.
<f: ajax listener="# {mybean.someaction}" render="somecomponent" />
The following code represents the someaction method in mybean.
Public void someaction(AjaxBehaviorEvent event) {
dosomething;
}
5.12 AJAX Basics
AJAX is an important front – end web technology that lets JavaScript
communicate with a web server. It lets you load new content without leaving
the current page, creating a better, faster experience for your web site’s visitors.
• Ajax stands for “Asynchronous JavaScript and XML”.
• The word “asynchronous” means that the user isn’t left waiting
for the server the respond to a request, but can continue using
the web page.
The typical method for using Ajax is the following:
1) A JavaScript creates an XMLHttpRequest object, initializes it
with relevant information as necessary, and sends it to the
server. The script (Or web page) can continue after sending it to
the server.

241
2) The server responds by sending the contents of a file or the
output of a server side program (written, for example, in PHP).
3) When the response arrives from the server, a JavaScript function
is triggered to act on the data supplied by the server.
4) This JavaScript response function typically refreshes the display
using the DOM, avoiding the requirement to reload or refresh
the entire page.
THE BASICS OF AJAX-RAILS WITH AJAX
Rails with AJAX
Ajax stands for Asynchronous JavaScript and XML. Ajax is not a single
technology; it is a suite of several technologies. Ajax incorporates the
following:
 XHTML for the markup of web pages
 CSS for the styling
 Dynamic display and interaction using the DOM
 Data manipulation and interchange using XML
 Data retrieval using XMLHttpRequest
 JavaScript as the glue that meshes all this together
Ajax enables you to retrieve data for a web page without having to
refresh the contents of the entire page. In the basic web architecture, the user
clicks a link or submits a form. The form is submitted to the server, which then
sends back a response. The response is then displayed for the user on a new
page.
When you interact with an Ajax-powered web page, it loads an Ajax
engine in the background. The engine is written in JavaScript and its
responsibility is to both communicate with the web server and display the
results to the user. When you submit data using an Ajax-powered form, the
server returns an HTML fragment that contains the server's response and
displays only the data that is new or changed as opposed to refreshing the entire
page.
How Rails Implements Ajax:
Rails have a simple, consistent model for how it implements Ajax
operations. Once the browser has rendered and displayed the initial web page,
different user actions cause it to display a new web page (like any traditional
web application) or trigger an Ajax operation:

242
 Some trigger fires :This trigger could be the user clicking on a button
or link, the user making changes to the data on a form or in a field, or
just a periodic trigger (based on a timer)
 The web client calls the server: A JavaScript method,
XMLHttpRequest, sends data associated with the trigger to an action
handler on the server. The data might be the ID of a checkbox, the text
in an entry field, or a whole form.
 The server does processing: The server-side action handler (Rails
controller action) -- does something with the data and returns an HTML
fragment to the web client.
 The client receives the response: The client-side JavaScript, which
Rails creates automatically, receives the HTML fragment and uses it to
update a specified part of the current page's HTML, often the content of
a <div> tag.
These steps are the simplest way to use Ajax in a Rails application, but
with a little extra work, you can have the server return any kind of data in
response to an Ajax request, and you can create custom JavaScript in the
browser to perform more involved interactions.
AJAX Example:
While discussing rest of the Rails concepts, we have taken an example
of Library. There we have a table called subject and we had added few subjects
at the time of Migration. Till now we have not provided any procedure to add
and delete subjects in this table.
In this example we will provide, list, show and create operations on
subject table. If you don't have any understanding on Library Info System
explained in previous chapters then I would suggest you to complete previous
chapters first and then continue with AJAX on Rails.
Creating Controller:
So let’s start with creation of a controller for subject, this will be done
as follows:

C:\ruby\library> ruby script/generate controller Subject

This command creates a controller file app/controllers/subject_


controller.rb. Open this file in any text editor and modify it to have following
content.

class SubjectController < ApplicationController


layout 'standard'

243
def list
end
def show
end
def create
end
end

Now we will give implementation for all these functions in the same
way we had given in previous chapters.
The list method implementation:

def list
@subjects = Subject.find(:all)
end

This is similar to the example explained earlier and will be used to list
down all the subjects available in our database.
The show method implementation:

def show
@subject = Subject.find(params[:id])
end

This is also similar to the example explained earlier and will be used to
display a particular subject corresponding to passed ID.
The create method implementation:

def create
@subject = Subject.new(params[:subject])
if @subject.save
render :partial => 'subject', :object => @subject
end
end

This is bit new here. Here we are not redirecting page to any other page
but just rendering only changed part instead of whole page.

244
This happens possible only when using partial. We don't write
complete view file, instead we will write a partial in /app/view/subject
directory. We will see it in a moment. First let's create view files for other
methods.
Creating Views:
Now we will create view files for all the methods except for create
method for which we will create a partial.
Creating view for list method:
Create a file list.rhtml in /app/view/subject and populate it with the
following code.

<h1>Listing Subjects</h1>
<ul id="subject_list">
<% @subjects.each do |c| %>
<li><%= link_to c.name, :action => 'show', :id => c.id %>
<%= "(#{c.books.count})" -%></li>
<% end %>
</ul>

How Rails Implements Ajax:


Rails have a simple, consistent model for how it implements Ajax
operations. Once the browser has rendered and displayed the initial web page,
different user actions cause it to display a new web page (like any traditional
web application) or trigger an Ajax operation:
 Some trigger fires :This trigger could be the user clicking on a button
or link, the user making changes to the data on a form or in a field, or
just a periodic trigger (based on a timer)
 The web client calls the server: A JavaScript
method, XMLHttpRequest, sends data associated with the trigger to an
action handler on the server. The data might be the ID of a checkbox,
the text in an entry field, or a whole form.
 The server does processing: The server-side action handler (Rails
controller action) -- does something with the data and returns an
HTML fragment to the web client.

245
The client receives the response: The client-side JavaScript, which Rails
creates automatically, receives the HTML fragment and uses it to update a
specified part of the current page's HTML, often the content of a <div> tag.
These steps are the simplest way to use Ajax in a Rails application, but
with a little extra work, you can have the server return any kind of data in
response to an Ajax request, and you can create custom JavaScript in the
browser to perform more involved.

246
NOTES
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………

247
NOTES
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………

248

You might also like