0% found this document useful (0 votes)
248 views228 pages

Web Technology Complete Notes

Uploaded by

ddmonk052
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
248 views228 pages

Web Technology Complete Notes

Uploaded by

ddmonk052
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 228

Course Contents:

Unit 1: Introduction (3 Hrs.) Web Basics: Internet, Intranet, WWW, Static and Dynamic Web
Page; Web Clients; Web Servers; Client Server Architecture: Single Tier, Two-Tier, Multi-Tier;
HTTP: HTTP Request and Response; URL, Client Side Scripting, Server Side Scripting, Web
1.0, Web 2.0

Unit 2: Hyper Text Markup Language (10 Hrs.) Introduction to HTML; Elements of HTML
Document; HTML Elements and HTML Attributes, Headings, Paragraph, Division, Formating:
b, i, small, sup, sub; Spacing: Pre, Br; Formatting Text Phrases: span, strong, tt; Image element;
Anchors; Lists: Ordered and Unordered and Definition; Tables; Frames; Forms: Form Elements,
ID attributes, Class Attributes of HTML Elements; Meta Tag, Audio, Video, Canvas, Main,
Section, Article, Header, Footer, Aside, Nav, Figure Tags; HTML Events: Window Events,
Form Element Events, Keyboard Events, Mouse Events

Unit 3: Cascading Style Sheets (8 Hrs.) Introduction; Cascadding Style Sheets (CSS); CSS
Syntax; Inserting CSS: Inline, Internal, External, ID and Class Selectors; Colors; Backgrounds;
Borders; Text; Font; List; Table; CSS Box Model; Normal Flow Box Layout: Basic Box Layout,
Display Property, Padding, Margin; Positioning: Relative, Float, Absolute; CSS3 Borders, Box
Shadows, Text Effects and shadow; Basics of Responsive Web Designs; Media Queries,
Introduction to Bootstrap

Unit 4: Client Side Scripting with JavaScript (9 Hrs.) Structure of JavaScript Program;
Variables and Data Types; Statements: Expression, Keyword, Block; Operators; Flow Controls,
Looping, Functions; Popup Boxes: Alert, Confirm, Prompt; Objects and properties;
Constructors; Arrays; Built-in Objects: Window, String, Number, Boolean, Date, Math, RegExp,
Form, DOM; User Defined Objects; Event Handling and Form Validation, Error Handling,
Handling Cookies, jQuery Syntax; jQuery Selectors, Events and Effects; Introduction to JSON

Unit 5: AJAX and XML (7 Hrs.) Basics of AJAX; Introduction to XML and its Application;
Syntax Rules for creating XML document; XML Elements; XML Attributes; XML Tree; XML
Namespace; XML schema languages: Document Type Definition(DTD), XML Schema
Definition (XSD); XSD Simple Types, XSD Attributes; XSD Complex Types; XML Style
Sheets (XSLT), Xquery

Unit 6: Server Side Scripting using PHP (8 Hrs.)

PHP Syntax, Variables, Data Types , Strings, Constants, Operators, Control structure, Functions,
Array, Creating Class and Objects, PHP Forms, Accessing Form Elements, Form Validation.

Events, Cookies and Sessions, Working with PHP and MySQL, Connecting to Database,
Creating, Selecting, Deleting, Updating Records in a table, Inserting Multiple Data, Introduction
to CodeIgniter, Laravel, Wordpress etc.

Text Books:

1. Web Design with HTML, CSS, JavaScript and jQuery Set, Jon Duckett, John Wiley & Sons

2. Web Technologies: A Computer Science Perspective, Jeffrey C. Jackson , Pearson Prentice


Hall

3. Learning PHP, MySQL & JavaScript: with jQuery, CSS & HTML5, Robin Nixon, O’Reilly

4. PHP & MySQL: Server-side Web Development, Jon Ducket, Wiley


Unit 1: Introduction (3 Hrs.)
Web Basics: Internet, Intranet, WWW, Static and Dynamic Web Page; Web Clients; Web
Servers; Client Server Architecture: Single Tier, Two-Tier, Multi-Tier;

HTTP: HTTP Request and Response; URL, Client Side Scripting, Server Side Scripting, Web
1.0, Web 2.0

Internet:
History:

 Its origin dates back to 1969 when it was called ARPAnet (Advanced Research Project
Agency network) and was exclusively used for military purposes. It soon emerged with non-
governmental and parallel academic networks which grew and eventually came to be called
Internet in the year 1979.
 Today, Internet is simply a network of world-wide network of computer networks connected
to each other by devices called Internetworking devices. The computers on the Internet
contains information on history, politics and medicine, science and technology, sports,
current events and many more topics and thus it is also called ‗information super highway‘.
The Internet is growing exponentially every day and has made the planet a ‗global village'
where everybody can be connected to everybody.
 The Internet is popular because it is:
 Ubiquitous (being everywhere at once)
 Open
 Easy
 Fast
 Proven
 Inexpensive
 Versatile (capable of doing many things)

Major applications of Internet:

1. Exchange emails.

2. Send/receive documents, sound, animation and graphics or picture files all over the world.

3. Video Calls

4. Browse information on matters related to academic and professional topics.


5. Join specific topic-oriented discussion groups - Blogs.

6. Buy/Sell products and services — i.e. E-commerce.

7. Entertainment (games, music, etc).

8. Download software and software updates.

9. Online education and exams.

10. Online Games (mobile games, web games)

Internet: A worldwide network of thousands of smaller computer networks and millions of


commercial, educational, government and personal computers. The Internet is like an electronic
city with virtual libraries, stores, art galleries and so on.

Intranet: A network within an organization that uses Internet technologies (such as the HTTP or
FTP protocol). By using hyperlinks, you can explore objects, documents, pages, and other
destinations on the Intranet.

Difference: The Internet is a global network. It is called network of networks. It contains


information in any sector - education, business, games, and lots more. Whereas Intranet is an
organizational based network. It is a closed network. Generally, the big companies having
branches at different places create this network for data sharing and for communication. They
find it more secure and cost effective rather than using Internet.

Intranet can be called internal Internet. Only the employees of the company can use this network.
They create their documents in the form of web pages and place them in the Intranet web servers
and all the employees of the company can view the web pages in the web browsers just by typing
the address in the address bar. So, in this way they transfer the data in a secure manner with the
help of Intranet-the closed network.

Extranet: An Extranet is an Intranet that supports controlled public access.

Extranets offer controlled access to an Intranet for remote access and e-commerce purposes.

WWW:

The World Wide Web (WWW) is most often called the Web.
The Web is a vast collection of documents that are linked together. A set of protocols define how
the system works and transfers data while a set of conventions and body of software makes it
work smoothly. It uses hypertext and multimedia techniques and supports many kinds of
documents such as text, formatted text, pictures, audio and video.
The inventor of WWW is Tim Berners Lee.
How does WWW works?
 Web information is stored in documents called Web pages.
 Web pages are files stored on computers called Web servers.
 Computers reading the Web pages are called Web clients.
 Web clients view the pages with a program called a Web browser.
 A web browser is a client software that allows you to display and interact with a hypertext
document hosted on the web server. Popular browsers are Google Chrome, Mozilla Firefox,
Opera, Internet Explorer and Netscape Navigator.
 A browser fetches a Web page from a server by a request.
 A request is a standard HTTP request containing a page address.
 A web page address looks like this:
 http://www.someone.com/page.htm
 All Web pages contain instructions for display.
 The browser displays the page by reading these instructions.
 The most common display instructions are called HTML tags.
 HTML tags look like this <p> This is a Paragraph </ p>.
Website:
Website is a collection of related web pages that may contain text, images, audio and video. The
first page of a website is called home page. Each website has specific internet address (URL) that
you need to enter in your browser to access a website.

Website is hosted on one or more servers and can be accessed by visiting its homepage using a
computer network. A website is managed by its owner that can be an individual, company or an
organization.

Static website
Static website is the basic type of website that is easy to create. You don't need the knowledge of
web programming and database design to create a static website. Its web pages are coded in
HTML.
The codes are fixed for each page so the information contained in the page does not change and
it looks like a printed page.

Figure: Static Website


Dynamic website

Dynamic website is a collection of dynamic web pages whose content changes dynamically. It
accesses content from a database or Content Management System (CMS). Therefore, when you
alter or update the content of the database, the content of the website is also altered or updated.

Dynamic website uses client-side scripting or server-side scripting, or both to generate dynamic
content.

Client side scripting generates content at the client computer on the basis of user input. The web
browser downloads the web page from the server and processes the code within the page to
render information to the user.

In server side scripting, the software runs on the server and processing is completed in the server
then plain pages are sent to the user.

Figure: Dynamic Website

Static vs Dynamic website


Static Website Dynamic Website
Prebuilt content is same every time the Content is generated quickly and changes
page is loaded. regularly.
It uses the HTML code for developing It uses the server side languages such as PHP,
a website. SERVLET, JSP, and ASP.NET etc. for
developing a website.
It sends exactly the same response for It may generate different HTML for each of
every request. the request.
The content is only changed when The page contains "server-side" code which
someone publishes and updates the file allows the server to generate the unique
(sends it to the web server). content when the page is loaded.
Flexibility is the main advantage of Content Management System (CMS) is the
static website. main advantage of dynamic website.
Web client:

The client or user, side of the Web. It typically refers to the Web browser in the user's
machine. It may also refer to plug-ins and helper applications that enhance the browser to
support special services from the site. The term may imply the entire user machine or refer to
a handheld device that provides Web access.

Web Server:

A Web server is a computer where the web content is stored. Basically web server is used to
host the web sites but there exists other web servers also such as gaming, storage, FTP, email etc.

It has two functions basically:

1. Connect to databases or other web server and get data


2. Get that data and pass in to the client (mostly browser or an App) which the client
had requested.

Note: There is always a connection between web clients and web servers because the request
sent by web client is responded by web server over network.

Client Server Architecture:

N-tier Architectures: 1-tier, 2-tier and 3-tier architecture.


Significance of “Tiers”
N-tier architectures have the same components
 Presentation
 Business/Logic
 Data
N-tier architectures try to separate the components into different tiers/layers
Tier: physical separation
Layer: logical separation

1-Tier Architecture
All 3 layers are on the same machine (standalone architecture):
1. All code and processing kept on a single machine Local System).
2. Presentation, Logic, Data layers are tightly connected
3. Scalability: Single processor means hard to increase volume of processing
4. Portability: Moving to a new machine may mean rewriting everything
5. Maintenance: Changing one layer requires changing other layers

2-Tier Architecture

1. Database runs on Server (Server can be found in Web)


2. Separated from client
3. Easy to switch to a different database
4. Heavy load on server
5. Presentation still tied to business logic

3-Tier Architecture

1. Each layer can potentially run on a different machine.


2. Presentation, logic, data layers disconnected.
HTTP: HTTP Request and Response; URL, Client Side Scripting, Server Side Scripting, Web
1.0, Web 2.0

HyperText Transfer Protocol (HTTP)


Definition:
The HTTP is an application protocol for distributed, collaborative, hypermedia information
systems. HTTP is the foundation of data communication for the World Wide Web. Hypertext is
structured text that uses logical links (hyperlinks) between nodes containing text. HTTP is the
protocol to exchange or transfer hypertext.

HTTP is a stateless, application-layer protocol for communicating between distributed systems,


and is the foundation of the modern web.

Origin:

Tim Berners-Lee and his team are credited with inventing the original HTTP along with HTML
and the associated technology for a web server and a text-based web browser. Berners-Lee first
proposed the "WorldWideWeb" project in 1989-now known as the World Wide Web. The first
version of the protocol had only one method, namely GET, which would request a page from a
server. The response from the server was always an HTML page.

How it works?

HTTP allows for communication between a variety of hosts and clients, and supports a mixture
of network configurations. To make this possible, it assumes very little about a particular system,
and does not keep state between different message exchanges. This makes HTTP a stateless
protocol. The communication usually takes place over TCP/IP, but any reliable transport can be
used. The default port for TCP/IP is 80, but other ports can also be used.

Communication between a host and a client occurs, via a request/response pair. The client
(Web browser) initiates an HTTP request message, which is serviced through a HTTP response
message in return. A web browser is an example of a user agent (UA). Other types of user agent
include the indexing software used by search providers (web crawlers), voice browsers, mobile
apps, and other software that accesses, consumes, or displays web content.
URLs

At the heart of web communications is the request message, which are sent via Uniform
Resource Locators (URLs). URLs have a simple structure that consists of the following
components:

The protocol is typically http, but it can also be https for secure communications. The default
port is 80, but one can be set explicitly. The resource path is the local path to the resource on
the server.

HTTP Verbs
URLs reveal the identity of the particular host with which we want to communicate, but the
action that should be performed on the host is specified via HTTP verbs. Of course, there are
several actions that a client would like the host to perform. Two commonly used verbs or
methods for a request-response between a client and server are: GET and POST.

 GET - Requests data from a specified resource


 POST - Submits data to be processed to a specified resource

Some notes on GET requests:


GET requests can be cached
GET requests remain in the browser history
GET requests can be bookmarked
GET requests should never be used when dealing with sensitive data
GET requests have length restrictions
GET requests should be used only to retrieve data
Some notes on POST requests:
POST requests are never cached
POST requests do not remain in the browser history
POST requests cannot be bookmarked
POST requests have no restrictions on data length
Status Codes
With URLs and verbs, the client can initiate requests to the server. In return, the server responds
with status codes and message payloads. The status code is important and tells the client how to
interpret the server response. Some status codes are:
 200 OK: This tells the client that the request was successfully processed.
 400 Bad Request: the request was malformed.
 401 Unauthorized: request requires authentication. The client can repeat the request with the
Authorization header. If the client already included the Authorization header, then the
credentials were wrong.
 403 Forbidden: server has denied access to the resource.
 404 Not Found: 404 indicates that the resource is invalid and does not exist on the server.
 500 Internal Server Error: It is used to indicate a server failure while processing the
request.
 503 Service Unavailable: this could happen if an internal system on the server has failed or
the server is overloaded. Typically, the server won't even respond and the requests will
timeout.

So, we've seen that URLs, verbs and status codes make up the fundamental pieces of an HTTP
request/response pair.
Client side and Server side Scripting Language:

 A scripting language is a simple programming language designed to enable computer users to


write useful programs easily.
 Scripting languages are interpreted, i.e. they are not compiled to any particular machine or
operating system. This is what makes them platform-independent.
 Scripts can be written for execution on client or the server. Scripts that get executed on the
client machine by a web browser are called client-side scripts whereas those that get
executed on the server are called server-side scripts.
 Actually, client-side scripting and server-side scripting languages are the scripting languages
generally used to give dynamic effect to the static HTML pages. Static web pages can
include forms but for the validation of form‘s information, we use scripting languages.
 Examples of client-side scripting languages are VBScript, JavaScript, Jscript and examples
of server-side scripting languages are ASP, PHP, Perl, etc.
 For the manipulation of server variables and server objects, we use server-side scripting
languages and client-side scripting language is used for writing interactive programs in web
pages. Server-side scripting languages also can include any client-side languages in their
pages. For example, JavaScript are included in ASP, PHP, Java, etc.

Web 1.0, web 2.0 and web 3.0

Web 1.0:

The first iteration of the web represents the web 1.0, which, according to Berners-Lee, is the
―read-only web.‖ In other words, the early web allowed us to search for information and read it.
There was very little in the way of user interaction or content generation.

Web 1 is one-way communication. Web 1.0 is informative web pages where the user has no role
in adding reviews, comments or feedback. E.g. some e-commerce sites that only shows items and
if user wants to buy it he/she has to order it from outside (phone calls) of that site.

Web 2.0:

Web 2 is two-way communication. Web 2.0 involves participation, information and data sharing,
collaboration. According to Berners-Lee, is the ―read-write on web‖. A user can interact in web
pages, a user can participate in comments, reviews, can post something, and can watch videos.
E.g. Youtube, Facebook, and many more web applications.

Web 3.0:

Web 3.0 includes many additional features that are embedded in web sites or web applications
that make users convenient to use it. Due to machine learning, artificial intelligence, natural
language processing web systems are now more advanced than they were in web 2.0. E.g.
Google search uses AI, YouTube also uses AI and filtering algorithm to recommend the videos
and pause videos if user becomes idle for long time.
Unit 2: Hyper Text Markup Language (10 Hrs.)
Introduction to HTML; Elements of HTML Document; HTML Elements and HTML
Attributes, Headings, Paragraph, Division, Formating: b, i, small, sup, sub; Spacing: Pre, Br;
Formatting Text Phrases: span, strong, tt; Image element; Anchors; Lists: Ordered and
Unordered and Definition; Tables; Frames; Forms: Form Elements, ID attributes, Class
Attributes of HTML Elements; Meta Tag, Audio, Video, Canvas, Main, Section, Article,
Header, Footer, Aside, Nav, Figure Tags; HTML Events: Window Events, Form Element
Events, Keyboard Events, Mouse Events.

Markup Language:

Markup language is used to format text into a specified format. It uses some predefined tags.
These tags are not so flexible and hence markup language possesses certain restrictions to the
web developers. A markup language is not a programming language because a programming
creates a set of instructions that are interpreted or compiled into a program or application. The
best example of a programming language is PHP, Java, etc. and HTML is a markup language.

<HTML> [Hyper Text Markup Language]

HTML stands for Hypertext Markup Language and it is the standard used by the world wide web
documents.
An HTML file is an ASCII text file containing small markup tags. The markup tags tell the Web
browser how to display the page. Since HTML uses ASCII text, the web documents are
delivered over the network such that they are not platform dependent. Hence only a web browser
is required which can interpret HTML files irrespective of whether it is running on a machine
using Windows or UNIX or Macintosh or on any other operating system or hardware platform.
An HTML file must have an .htm or .html file extension.

Additional information about HTML;


HTML is the most widely used language on Web to develop web pages. HTML was created by
Berners-Lee in late 1991 but "HTML 2.0" was the first standard HTML specification which was
published in 1995. HTML 4.01 was a major version of HTML and it was published in late 1999.
Though HTML 4.01 version is widely used but currently we are having HTML-5 version which
is an extension to HTML 4.01, and this version was published in 2012.
All html pages should contain four basic HTML elements:
HTML
HEAD
TITLE
BODY

General HTML Template for All Web Pages


<html>
<head>
<title> Title of a web page (can be seen on browser’s window title bar)</title>
</head>
<body>
This is the main part of any web page. The text and graphics inside the body
elements are displayed in the browser’s web page display.
</body>
</html>

Descriptions:
 The first tag in your HTML document is <html>. This tag tells your browser that this is
the start of an HTML document. The last tag in your document is </html>. This tag tells
your browser that this is the end of the HTML document.
 The text between the <head> tag and the </head> tag is header information. Header
information is not displayed in the browser‘s window.
 The text between the <title> tags is the title of your document. The title is displayed in
your browser's caption.
 The text between the <body> tags is the text that will be displayed in your browser.

Note: The visible elements of a Web page generally go inside of the BODY of the page.

HTML tags:
 HTML documents are text files made up of HTML elements. HTML elements are
defined using HTML tags.
 HTML Tags
◦ HTML tags are used to mark-up HTML elements.
◦ HTML tags are surrounded by the two characters < and >. The surrounding
characters are called angle brackets.
◦ HTML tags are of two types: empty tag like <br> and container tag or pair tag
(on-off type) like <p> and </p>. The first tag in a pair is the start tag, the second
tag is the end tag. The text between the start and end tags is the element content.
◦ HTML tags are case insensitive i.e. <b> means the same as <B>.

HTML Elements and Attributes:


So far we have studied general tags (html, head, title, body). But there are so many tags that are
used in html document for different purposes e.g. <p> tag, <b> tag, <i> tag, <div> tag, <h1>,
<h2>, ….. <h6> tags. We do have some empty tags which do not contain any contents such as
<br /> tag, <hr /> tags for line break and horizontal line break respectively. There are six heading
tags that are used to display the text as per the pre-defined size of text. E.g. Headings come in six
sizes, ranging from <H1>very large</H1> to <H6>very small</H6>.

Example:

<html>
<head>
<title>
Heading Tag Demonstration
</title>
</head>
<body>
<h1>This is a heading</h1>
<h2 align=center>This is a heading</h2>
<h3>This is a heading</h3>
<h4 align=right>This is a heading</h4>
<h5>This is a heading</h5>
<h6>This is a heading</h6>
</body>
</html>
HTML Attributes:
Attributes are the additional information of that specific tag provided by any html or element in
any html or xml document. E.g. <body bgcolor = ―green‖>…… </body>, <body style=
―background-color: green>…. <body>, <table border = 1>, <h2 align = ―center‖>, and many
more. Attributes play an important role in changing the appearance of any html tag. We can
easily embed the css with the help of style attribute in any html tag.
Example:
<html>
<head> <title> HTML Attributes </title> </head>

<body bgcolor = “blue”>


<div style = “background-color: green”>
<p style = “color: red”> Hello I am the student of semester 5. </p>
</div>
<table border = 2>
<tr>
<th>Name</th>
<th>Roll no</th>
</tr>
<tr>
<td>Harendra</td>
<td>24</td>
</tr>
</table>
</body>
<html>

<p> Tag in html document:


The <p> tag defines a paragraph. Browsers automatically add a single blank line before and after
each <p> element.

<div> Tag in html document:


The <div> tag defines a division or a section in an HTML document. It is used as a container for
HTML elements - which is then styled with CSS or manipulated with JavaScript. It is easily
styled by using the class or id attribute. Any content or tags can be put inside the <div> tag.

Note: By default, browsers always place a line break before and after the <div> element.
Comments in html document:

 The comment tag is used to insert a comment in the HTML source code.
 Comments are ignored by the browser.
 You can use comments to explain your code, which can help you when you edit the source code
at a later date.
 Example: <!-- This is a comment -->
 Note that you need an exclamation point after the opening bracket, but not before the closing
bracket.

Text Formatting tags:


Tag Description
<b> Defines bold text
<big> Defines big text
<em> Defines emphasized text
<i> Defines italic text
<u> Defines underlined text
<small> Defines small text
<strong> Defines strong text
<sub> Defines subscripted text
<sup> Defines superscripted text
Example:
<!--text formatting tags.htm-->
<html>
<body>
<b>This text is bold</b>
<br>
<strong>This text is strong</strong>
<br>
<big>This text is big</big>
<br>
<em>This text is emphasized</em>
<br>
<i>This text is italic</i>
<br>
<small>This text is small</small>
<br>
This text contains<sub>subscript</sub>
<br>
This text contains<sup>superscript</sup>
</body>
</html>
Question:
Create an HTML document with the program using <p>, <h1>, <strong> for first word of every
sentence and <em> for all the capital letters.
Answer:

<!DOCTYPE html>
<html>
<head>
<title>Solution</title>
</head>
<body>
<p><h1><strong>My</strong></h1></p> name is<em>HARENDRA RAJ BIST</em>.
<p><h1><strong>I</strong></h1></p> live in<em>KALANKI</em> Naikap.
</body>
</html>

Preformatted text display

 We should never try to format the text in the editor by adding empty lines and spaces to the
text. HTML will truncate the spaces in your text. Any number of spaces count as one.

 However, with the <pre>…</pre> tag, we can include text which was edited by a text editor
and preserve the original text formatting such as tabs, end of line, etc.

 The HTML Teletype Text Element ( <tt> ) produces an inline element displayed in the
browser's default monotype font. This element was intended to style text as it would display
on a fixed width display, such as a teletype. It probably is more common to display fixed
width type using the <code> element.
<html>
<body>
<pre>
This is
preformatted text.
It preserves both spaces
and line breaks.
</pre>
<p><tt>The pre tag is good for displaying</tt> computer code:</p>
<pre>
for i = 1 to 10
print i
next i
</pre>
</body>
</html>

<hr> and <address> tag:

<hr> Tag

The <hr> tag adds a horizontal line.

Color can be given to the horizontal line as

<hr color = ―red‖>

It is empty tag.

<address> Tag

The <address> tag is mainly used to write address.


It begins with <address> and ends with </address>.
The <address> tag makes the text italic.
<span>tag:

The <span> tag is an inline container used to mark up a part of a text, or a part of a document.
The <span> tag is easily styled by CSS or manipulated with JavaScript using the class or id attribute.
The <span> tag is much like the <div> element, but <div> is a block-level element and <span> is an
inline element.
Example:

<p>We are studying in <span style="color:blue">Semester</span> Five.</p>

HTML links (anchor tag)

HTML uses a hyperlink to link to another document on the Web. HTML uses the <a> (anchor) tag to
create a link to another document. An anchor can point to any resource on the Web: an HTML page,
an image, a sound file, a movie, etc.

The syntax of creating an anchor is:

<a href=“URL">Text to be displayed</a>

The <a> tag is used to create an anchor to link from, the href attribute is used to address the
document to link to, and the words between the open and close of the anchor tag will be displayed as
a hyperlink.

This anchor defines a link to vedas college :

<a href="https://www.vedascollge.edu.com.np /">Visit Our College’s Site!</a>

Link to any other document;

<html>
<body>
<a href=“test.htm”>Test Page</a>
The link will open in the same window.
<a href=“test.htm” target=_blank>Test Page</a>
The link will open in the different window or tab.
</body>
</html>

The name attribute in anchor tag:

The name attribute is used to create a named anchor. When using named anchors we can create links
that can jump directly into a specific section on a page, instead of letting the user scroll around to
find what he/she is looking for. Below is the syntax of a named anchor:
 <a name="label">Text to be displayed</a>
The name of the anchor can be any text you care to use. The line below defines a named anchor:
 <a name="tips">Useful Tips Section</a>
You should notice that a named anchor is not displayed in a special way.
To link directly to the "tips" section, add a # sign and the name of the anchor to the end of a URL,
like this:
 <a href="#tips">Jump to the Useful Tips Section</a>
Example:

<!--anchor_within_page.htm-->
<html>
<body>
<p>
<a href="#C8">Jump to Chapter 8.</a>
</p>
<p>
<a name="C1"><h2>Chapter 1</h2></a>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 2</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 3</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 4</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 5</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 6</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 7</h2>
<p>This chapter explains ba bla bla</p>
<br>
<a name="C8"><h2>Chapter 8 <a href="#C1">Go to Top</a></h2></a>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 9</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 10</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 11</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 12</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 13</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 14</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 15</h2>
<p>This chapter explains ba bla bla</p>
</body>
</html>

Using image as link:

<!--image.htm-->
<html>
<body>
You can also use an image as a link:
<a href="test.htm">
<img src="file://C://Users/DESKTOP-L7LVCJU/Desktop/pp.jpg" width="100"
height=“100" alt="My Pic"> </a>

</body>
</html>

Image Element:

 With HTML you can display images in a document.


 The Image Tag and the Source Attribute: In HTML, images are defined with the <img> tag. The
<img> tag is empty, which means that it contains attributes only and it has no closing tag.
 To display an image on a page, you need to use the src attribute which stands for "source". The
value of the src attribute is the URL of the image you want to display on your page. The syntax
of defining an image is:
 <img src="url">
 The URL points to the location where the image is stored. An image named ―ace.gif" located in
the directory "images" on "www.xyz.com.np" has the URL: http://www.xyz.com.np/ace.gif.
 The browser puts the image where the image tag occurs in the document. If you put an image tag
between two paragraphs, the browser shows the first paragraph, then the image, and then the
second paragraph.
 The Alt Attribute: The alt attribute is used to define an "alternate text" for an image. The value
of the alt attribute is an author-defined text such as:
 <img src=―ace.gif" alt=―Ace of Spades">
 The "alt" attribute tells the reader what he or she is missing on a page if the browser can't load
images. The browser will then display the alternate text instead of the image. It is a good practice
to include the "alt" attribute for each image on a page, to improve the display and usefulness of
your document for people who have text-only browsers.
Note: Loading images take time, so the best advice is: Use img’s alt property.
Example:

<img src="mountain.jpg" alt="Mountain" width="500" height="600">

<img src="mountain.jpg" alt="Mountain" style =”width:500;height:600;">

HTML Lists:

 Lists are collection of items.


 HTML supports ordered, unordered and definition lists.

Unordered Lists:
An unordered list is a list of items. The list items are marked with bullets (typically small black
circles).
 An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
 To change the shape of the bullets, do as follows:
 <ul type = “square”>
Example:
<ul>
<li>Web Technology</li>
<li>Design and Analysis of Algorithm</li>
</ul>

Type attribute of <ul> tag:


<!--unordered_list.htm-->
<html>
<body>
<h4>Disc bullets list:</h4>
<ul type="disc">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ul>
<h4>Circle bullets list:</h4>
<ul type="circle">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ul>
<h4>Square bullets list:</h4>
<ul type="square">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ul>
<h4>Normal list:</h4>
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ul>
</body>
</html>
Oredered List

 An ordered list is also a list of items. The list items are marked with numbers.
 An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.
 If you want to start the list from some other number say 101, then do as follows: <ol type = ―1‖
start = ―101‖>.
 To change the format of the ordered list, say starting from roman number I, then do as follows:
<ol type = “I”>.

Example:
<ol>
<li>Harendra</li>
<li>Narendra</li>
</ol>

Type attribute of <ol> tag:

<!--ordered_list.htm-->
<html>
<body>
<h4>Numbered list:</h4>
<ol>
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ol>
<h4>Letters list:</h4>
<ol type="A">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ol>
<h4>Lowercase letters list:</h4>
<ol type="a">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ol>
<h4>Roman numbers list:</h4>
<ol type="I">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ol>
<h4>Lowercase Roman numbers list:</h4>
<ol type="i">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ol>
<h4>Start from 101:</h4>
<ol type = "1" start = "101">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ol>
</body>
</html>

Nested List:

The list either ordered or unordered placed inside another list either ordered or unordered is known as nested
list.

Example:

<!--nested_list.htm-->
<html>
<body>
<h4>A nested List:</h4>
<ul>
<li>Coffee</li>
<li>Tea</li>
<ul>
<li>Black tea</li>
<li>Green tea</li>
<ul>
<li>China</li>
<li>Africa</li>
</ul>
</ul>
<li>Milk</li>
</ul>
</body>
</html>

Definition List:

 A definition list is not a list of items. This is a list of terms and explanation of the terms.

 A definition list starts with the <dl> tag. Each definition-list defines definition term with the <dt> tag.
Each definition-list’s definition description starts with the <dd> tag.

Example:

<dl>

<dt>Coffee</dt>

<dd>Black hot drink</dd>

<dt>Milk</dt>

<dd>White cold drink</dd>

</dl>

HTML Tables:

 Tables are defined with the <table> tag. A table is divided into rows (with the <tr> tag), and each row
is divided into data cells (with the <td> tag). The letters td stands for "table data," which is the content
of a data cell. A data cell can contain text, images, lists, paragraphs, forms, horizontal rules, tables,
etc.

 Headings in a table are defined with the <th> tag.


Example:
<!--table.htm-->
<table border="1">
<th>Heading</th>
<th>Another Heading</th>
<tr>
<td>Row 1, cell 1</td>
<td>Row 1, cell 2</td>
</tr>
<tr>
<td>Row 2, cell 1</td>
<td>Row 2, cell 2</td>
</tr>
</table>

Table cell spanning:

There are two types off cell spanning in table properties, they are colspan and rowspan. Colspan merges two
or more columns while rowspan merges two or more rows.

Example

<!--cell_span.htm-->
<html>
<body>
<h4>Cell that spans two columns:</h4>
<table border="8">
<tr>
<th>Name</th>
<th colspan="2">Telephone</th>
</tr>
<tr>
<td>Bill Gates</td>
<td>555 77 854</td>
<td>555 77 855</td>
</tr>
</table>
<h4>Cell that spans two rows:</h4>
<table border="1">
<tr>
<th>First Name:</th>
<td>Bill Gates</td>
</tr>
<tr>
<th rowspan="2">Telephone:</th>
<td>555 77 854</td>
</tr>
<tr>
<td>555 77 855</td>
</tr>
</table>
</body>
</html>

Output:

Cellpadding: It is used to create more whitespace between the cell content and its borders.

Example:
<!--cellpadding.htm-->
<html>
<body>
<h4>Without cellpadding:</h4>
<table border="1">
<tr>
<td>First</td>
<td>Row</td>
</tr>
<tr>
<td>Second</td>
<td>Row</td>
</tr>
</table>
<h4>With cellpadding:</h4>
<table border="1" cellpadding="10">
<tr>
<td>First</td>
<td>Row</td>
</tr>
<tr>
<td>Second</td>
<td>Row</td>
</tr>
</table>
</body>
</html>
Output:

Cellspacing: It is used to create white spaces between cells of a table. It is used to increase the distance
between the cells.

Example:
<!--cellspacing.htm-->
<html>
<body>
<h4>Without cellspacing:</h4>
<table border="1">
<tr>
<td>First</td>
<td>Row</td>
</tr>
<tr>
<td>Second</td>
<td>Row</td>
</tr>
</table>
<h4>With cellspacing:</h4>
<table border="1" cellspacing="10">
<tr>
<td>First</td>
<td>Row</td>
</tr>
<tr>
<td>Second</td>
<td>Row</td>
</tr>
</table>
</body>
</html>

Output:
Adding background to table (color or picture/mage)
Table tag can use two background properties of adding background colour and background image. To add
background color, we can use bgcolor attribute in <table> tag. And to add background image we can use
background attribute in <table> tag and provide the image file source url in that attribute.
Example:
<!--table_background.htm-->
<html>
<body>
<h4>Adding background color:</h4>
<table border="1" bgcolor="red">
<tr>
<td>First</td>
<td>Row</td>
</tr>
<tr>
<td>Second</td>
<td>Row</td>
</tr>
</table>
<h4>Adding background image:</h4>
<table border="1" background="file://C://Users/ACER/Desktop/dp.jpg" width=200 height=200>
<tr>
<td>First</td>
<td>Row</td>
</tr>
<tr>
<td>Second</td>
<td>Row</td>
</tr>
</table>
</body>
</html>
Output

HTML frames:

 With frames, you can display more than one Web page in the same browser window or in other words
with frames, you can display more than one HTML document in the same browser window. Each HTML
document is called a frame, and each frame is independent of the others.
 The disadvantages of using frames are:
 The web developer must keep track of more HTML documents.
 It is difficult to print the entire page.

<frameset> and <frame> tags:


The <frameset> tag defines how to divide the window into frames. Each frameset defines a set of rows or
columns. The values of the rows/columns indicate the amount of screen area each row/column will occupy.
The <frame> tag defines what HTML document to put into each frame.
In the example below, we have a frameset with two columns. The first column is set to 25% of the width of
the browser window. The second column is set to 75% of the width of the browser window. The HTML
document "frame_a.htm" is put into the first column, and the HTML document "frame_b.htm" is put into the
second column:
<frameset cols="25%,75%">
<frame src="frame_a.htm"> //this frame shown in 25%
<frame src="frame_b.htm"> //this frame shown in 75%
</frameset>
Note: If a frame has visible borders, the user can resize it by dragging the border. To prevent a user from
doing this, you can add noresize="noresize" to the <frame> tag.
Example:
<!--frame.htm-->
<html>
<frameset rows="50%, 50%">
<frame noresize = "noresize" src="frame_a.htm"> <!--Now row can't be resized-->
<frameset cols="25%, 75%">
<frame src="frame_b.htm"> <!--col can be resized-->
<frame src="frame_c.htm">
</frameset>
</frameset>
</html>

Navigation Frame:

The navigation frame contains a list of links with the second frame as the target.

Let us first create a file called ―html_contents.htm" which contains three links. The source code of the file is:

<!--html_contents.htm-->

<html>

<a href ="frame_a.htm" target = "showframe">Frame a</a><br>

<a href ="frame_b.htm" target = "showframe">Frame b</a><br>

<a href ="frame_c.htm" target = "showframe">Frame c</a>

</html>

Next create another file called ―navigation_frame.htm‖ follows:

<!--navigation_frame.htm-->

<html>

<frameset cols="15%,*">

<frame src="html_contents.htm">

<frame src="frame_a.htm" name = "showframe"> //by default it is seen in 85% of window.

</frameset>

</html>
<iframe> tag:

<html>
<body>
<p>We are using iframe for three different web links (url) </p>
<iframe src="https://www.example.com/" width="600" height="500"></iframe>
<iframe src="https:/www./vedascollege.edu.np/" width="600" height="500"></iframe>
<iframe src="https://www.arihantholidays.com/" width="600" height="500"></iframe>
</body>
</html>

HTML Forms:

HTML Forms are used to select different kinds of user input.


Form: A form is an area that can contain form elements. Form elements are elements that allow the
user to enter information (like text fields, textarea fields, drop-down menus, radio buttons,
checkboxes, etc.) in a form. A form is defined with the <form> tag. For example,
<form>
<input>
……………..
<input>
</form>

Input: The most used form tag is the <input> tag. The type of input is specified with the type
attribute. The most commonly used input types are explained below:

1. Text Fields: Text fields are used when you want the user to type letters, numbers, etc. in a form.

<form>
First name:
<input type="text" name="firstname">
<br>
Last name:
<input type="text" name="lastname">
</form>
2. Radio Buttons: Radio Buttons are used when you want the user to select one of a limited
number of choices.
<form>
<input type="radio" name=“gender" value="male"> Male
<br>
<input type="radio" name=" gender " value="female"> Female
</form>
3. Check Boxes: Checkboxes are used when you want the user to select one or more options of a
limited number of choices.

<form>
<input type="checkbox" name="bike"> I have a bike
<br>
<input type="checkbox" name="car"> I have a car
</form>
4. Drop-down box: A drop-down box is a selectable list.

<form>
<select name="cars">
<option value="volvo">Volvo
<option value=“toyota">Toyota
<option value="fiat">Fiat
<option value=“hyuandai">Hyuandai
</select>
</form>
5. Textarea: Used to create a text-area (a multi-line text input control). A user can write text in the
text-area. In a text-area you can write an unlimited number of characters.

<textarea rows="10" cols="30">

Write anything inside.

</textarea>
Forms attributes and submit button:

When the user clicks on the "Submit" button, the content of the form is sent to another file. The
form's action attribute defines the name of the file to send the content to. The file defined in the
action attribute normally does something with the received input. And, method attribute sends the
data according to its type get or post. Apart from these, there may be onsubmit attribute which is
actually used whenever we want to call the JavaScript function while form is submitted.

<form name="input" action=“url” method="get">

Username:

<input type="text" name="user">

<input type="submit" value="Submit">

</form>

Types of button used inside a <form> tag are as follows;

 <input type=“submit” → sends form to server value=“submit”>


 <input type=“reset” → resets form values value=“submit” >
 <input type=“button” → just a placeholder value=“submit”

id and class attributes of html tags:

The attributes like id and class can be used almost in every tag to differentiate the tags and make
them unique by providing different ids and classes attributes.

E.g.
<p id =”testid” > hello every one </p>
<p id = “pid”> Namaste all of you </p>
Both p tags are unique. Usually id and class tag are used to change the css and to access for
JavaScript usage.
Example:
<html>
<body>
<p > hello every one </p>
<p id = “pid”> Namaste all of you </p>
<div class = “testclass”>
<p> This paragraph is inside the div tag. </p>
</div>
</body>
</html>
<style>

p{color:blue;} //this changes the color of all p tag’s content

#pid{color:green;} //this changes only the color of p tag of id pid.

.testclass {color:red;} //this changes the color of p tag inside div tag.

</style>

Meta Tag:

 The head element contains general information (meta-information) about a document. HTML also
includes a meta element that goes inside the head element. The purpose of the meta element is to provide
meta-information about the document. Most often the meta element is used to provide information that is
relevant to browsers or search engines like describing the content of your document.
 Keywords for Search Engines: Some search engines on the WWW use the name and content attributes of
the meta tag to index your pages. For example, this meta element defines a description of your page:
 <meta name="description" content="Free Web tutorials on HTML, CSS, and JavaScript">
 Also, this meta element defines keywords for your page:
 <meta name="keywords" content="HTML, DHTML, CSS, JavaScript, PHP">

<meta charset="UTF-8">

 Unicode is a character set. UTF-8 is encoding.

 Unicode is a list of characters with unique decimal numbers (code points). A = 65, B = 66, C =
67, ....(ASCII)

 This list of decimal numbers represent the string "hello": 104 101 108 108 111

 Encoding is how these numbers are translated into binary numbers to be stored in a computer:

 UTF-8 encoding will store "hello" like this (binary): 01101000 01100101 01101100
01101100 01101111

 Character sets translates characters to numbers. Encoding translates numbers into binary.
Audio, Video and Canvas tags:

Audio <audio> tag:

It is used to insert any audio file at some part of html document, so that it will easy to any user to hear the
audio sound in a web page. <audio> tag is a root element, if we need to show the controls on UI then we need
to include controls attribute in <audio> tag. Source <source> tag is included inside <audio> tag and is used
for external source file with its type.
There are three supported audio formats in HTML: MP3, WAV, and OGG.
Example:
<audio controls autoplay loops muted>
<html> </audio>
<body>
<audio controls>
<source src="funnydance.mp3" type="audio/mpeg">
</audio>
</body>
</html>

Video <video> tag:


HTML5 has a native video element that supports three video formats (MP4, WebM and Ogg),
making it much easier to embed videos in a webpage. You can define the external source for the
video using a file or a URL.
Example:
<!DOCTYPE html>
<html> <video height="200px" width="200px" controls autoplay loops poster="image/hello.png" muted>
</video>
<body>
<video width="400" controls>
<source src="funnydance.webm" type="video/mp4">
</video>
<p>
Video courtesy of
<a href="https://www.youtube.com/watch?v=FzG4uDgje3M" target="_blank">Test</a>.
</p>
</body>
</html>
Canvas <canvas> tag in html:

 The HTML5 <canvas> tag is used to draw graphics via scripting (usually JavaScript).
 However, the <canvas> element has no drawing abilities of its own (it is only a container for graphics) -
you must use a script to actually draw the graphics.
 The getContext() method returns an object that provides methods and properties for drawing on the
canvas.
 This reference will cover the properties and methods of the getContext("2d") object, which can be used to
draw text, lines, boxes, circles, and more - on the canvas.

Example:

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="800" height="800" style="border:1px solid #d3d3d3;backgrou
nd-color:antiquewhite;">
</canvas>
<script> //for circle
var c = document.getElementById("myCanvas"); ctx.beginPath();
ctx.arc(200, 100, 50, 0, 2 * Math.PI);//
var ctx = c.getContext("2d"); (200,100)-center, 50-radius, 0-start angle,
2PI=360-endangle
ctx.moveTo(0, 0); //initial point position is (0,0) ctx.stroke();
ctx.lineTo(500, 700); //final position point of a line
ctx.stroke(); //strokes by drawing from 500 to 700
</script>
Note: There are too many functions for canvas to draw different shapes such as rectangle, circle, etc. do more
examples if you find its really interesting.

Semantic and non-semantic elements in HTML:

Semantic elements of html are those elements which clearly shows what actually the contents inside that
particular tag is.
 <h1> to <h6>
 <p>
 <b>,<i>,<u>,
 <img>,etc
 Tells what actually the content is.
Non-semantic elements are those inside which the contents are not pre-defined. For ecample;
 <span>
 <div>
 Tells nothing about its content
New Semantic tags in html:

<article>
<aside>
<header>
<details>
<figcaption>
<nav>
<figure>
<footer>
<header> <section>
<main> <aside>
<mark> <article>
<nav>
<section>
<footer>
<summary>
<time>
Figure: UI for Semantic Elements

Why use semantic elements?


To look at the benefits of semantic elements, here are two pieces of HTML code. This first block of
code uses semantic elements:
<header></header>
<section>
<article>
<figure>
<img>
<figcaption></figcaption>
</figure>
</article>
</section>
<footer></footer>
Semantic elements are very useful in search engine optimization by identifying the actual
positioning of the header, footer, section, article, etc.
Whilst this second block of code uses non-semantic elements:
<div id="header"></div>
<div class="section">
<div class="article">
<div class="figure">
<img>
<div class="figcaption"></div>
</div>
</div>
</div>
<div id="footer"></div>
By using the semantic tags only the contents are not placed in a correct place as shown in figure above but for
the actual positioning of semantic tags in effect we need to write css for all these tags.

Example:

1. The <article> element specifies independent, self-contained content.


<article>
<h1>What Article do?</h1>
<p>Article is used to write heading with its descriptions. Kind of news in any newspaper. </p>
</article>
2. <nav>
<a href="/html/">HTML</a> |
<a href="/css/">CSS</a> |
<a href="/js/">JavaScript</a> |
<a href="/jquery/">jQuery</a>
</nav>
3. <p>Aside tage</p>
<aside>
<h4>Whrer it can be placed?</h4>
<p>It can be placed aside the web page. E.g. Recommentde videos in youtube are shown in
aside.</p>
</aside>
4. <footer>
<p>@copyright: Harendra</p>
<p>Contact information: <a href="mailto:[email protected]">
[email protected]</a>.</p>
</footer>

HTML Events: Window Events, Form Element Events, Keyboard Events, Mouse Events

An event is an effect produced after processing the html elements. Concept of event is whenever a window is
loaded or closed there occurs window event and are handled by attributes such as onload in <body> tags.

Window Events:

Events triggered for the window object (applies to the <body> tag):
Attribute Value Description
onafterprint script Script to be run after the document is printed
onbeforeprint script Script to be run before the document is printed
onbeforeunload script Script to be run when the document is about to be unloaded
onerror script Script to be run when an error occurs
onhashchange script Script to be run when there has been changes to the anchor part of the
a URL
onload script Fires after the page is finished loading
onmessage script Script to be run when the message is triggered
onoffline script Script to be run when the browser starts to work offline
ononline script Script to be run when the browser starts to work online
onpagehide script Script to be run when a user navigates away from a page
onpageshow script Script to be run when a user navigates to a page
onpopstate script Script to be run when the window's history changes
onresize script Fires when the browser window is resized
onstorage script Script to be run when a Web Storage area is updated
onunload script Fires once a page has unloaded (or the browser window has been
closed)

Example: <button onclick="getElementById('demo').innerHTML = Date()">What is the time?</button>


Form Events
Events triggered by actions inside a HTML form (applies to almost all HTML elements, but is most
used in form elements):
Attribute Value Description
onblur script Fires the moment that the element loses focus
onchange script Fires the moment when the value of the element is changed
oncontextmenu script Script to be run when a context menu is triggered
onfocus script Fires the moment when the element gets focus
oninput script Script to be run when an element gets user input
oninvalid script Script to be run when an element is invalid
onreset script Fires when the Reset button in a form is clicked
onsearch script Fires when the user writes something in a search field (for
<input="search">)
onselect script Fires after some text has been selected in an element
onsubmit script Fires when a form is submitted

Keyboard Events
Attribute Value Description
onkeydown script Fires when a user is pressing a key
onkeypress script Fires when a user presses a key
onkeyup script Fires when a user releases a key

Mouse Events
Attribute Value Description
onclick script Fires on a mouse click on the element
ondblclick script Fires on a mouse double-click on the element
onmousedown script Fires when a mouse button is pressed down on an element
onmousemove script Fires when the mouse pointer is moving while it is over an element
onmouseout script Fires when the mouse pointer moves out of an element
onmouseover script Fires when the mouse pointer moves over an element
onmouseup script Fires when a mouse button is released over an element
onwheel script Fires when the mouse wheel rolls up or down over an element
Source: www.w3schools.com
Unit 3: Cascading Style Sheets (8 Hrs.)
Introduction: Cascadding Style Sheets (CSS); CSS Syntax; Inserting CSS: Inline, Internal, External, ID
and Class Selectors; Colors; Backgrounds; Borders; Text; Font; List; Table; CSS Box Model; Normal
Flow Box Layout: Basic Box Layout, Display Property, Padding, Margin; Positioning: Relative, Float,
Absolute; CSS3 Borders, Box Shadows, Text Effects and shadow; Basics of Responsive Web Designs;
Media Queries, Introduction to Bootstrap.

Cascading Style Sheets:


CSS is used to style HTML elements.
– CSS stands for Cascading Style Sheets.
– Styles define how to display HTML elements.
– Styles are normally stored in Style Sheets.
– External Style Sheets can save you a lot of work.
– External Style Sheets are stored in CSS files.
– Multiple style definitions will cascade into one.
Syntax of CSS
 The CSS syntax is made up of three parts: a selector, a property and a value as:
 selector {property: value}
 The selector is normally the HTML element/tag you wish to define, the property is the attribute you wish
to change, and each property can take a value. The property and value are separated by a colon and
surrounded by curly braces:
 body {color: black}
 If the value is in multiple words, put quotes around the value:
 p {font-family: "sans serif"}
 If you wish to specify more than one property, you should separate each property with a semi-colon. The
example below shows how to define a center aligned paragraph, with a red text color:
 p {text-align:center;color:red}
 To make the style definitions more readable, you can describe one property on each line, like this:
p
{
text-align: center;
color: black;
font-family: arial ;
}
 Grouping: You can group selectors. Separate each selector with a comma. In the example below we have
grouped all the header elements. Each header element will be green:

h1,h2,h3,h4,h5,h6
{
color: green
}
 The class Selector: With the class selector you can define different styles for the same type of HTML
element. Say that you would like to have two types of paragraphs in your document: one right-aligned
paragraph, and one center-aligned paragraph. Here is how you can do it with styles:
p.right {text-align: right}
p.center {text-align: center}
 You have to use the class attribute in your HTML document:
<p class="right">
This paragraph will be right-aligned.
</p>
<p class="center">
This paragraph will be center-aligned.
</p>
 The class Selector…:
Only one class attribute can be specified per HTML element! The example below is wrong:
<p class="right" class="center">
This is a paragraph.
</p>
 You can also omit the tag name in the selector to define a style that will be used by all HTML elements
that have a certain class. In the example below, all HTML elements with class="center" will be center-
aligned:
.center {text-align: center}
 In the code below both the h1 element and the p element have class="center". This means that both
elements will follow the rules in the ".center" selector:
<h1 class="center">
This heading will be center-aligned
</h1>
<p class="center">
This paragraph will also be center-aligned.
</p>
 The id Selector: The id selector is different from the class selector! While a class selector may apply to
SEVERAL elements on a page, an id selector should always apply to only ONE element.
 An ID attribute must be unique within the document. The style rule below will match a p element that has
the id value "para1":
p#para1
{
text-align: center;
color: red
}
 The style rule below will match the first element that has the id value "wer345":
#wer345 {color: green}
 The rule above will match this h1 element:
<h1 id="wer345">Some text</h1>
 The style rule below will match a p element that has the id value "wer345":
p#wer345 {color: green}
 The rule above will not match this h2 element:
<h2 id="wer345">Some text</h2>
 CSS Comments: You can insert comments in CSS to explain your code, which can help you when you edit
the source code at a later date. A comment will be ignored by the browser. A CSS comment begins with
"/*", and ends with "*/", like this:
/* This is a comment */
p
{
text-align: center;
/* This is another comment */
color: black;
font-family: arial
}

Inserting CSS:
When a browser reads a style sheet, it will format the document according to it. There are three ways of
inserting a style sheet:
1. External Style Sheet
2. Internal Style Sheet
3. Inline Styles

1. External Style Sheet


An external style sheet is ideal when the style is applied to many pages. With an external style sheet, you can
change the look of an entire Web site by changing one file. Each page must link to the style sheet using the
<link> tag. The <link> tag goes inside the head section.
<head>
<link rel="stylesheet" type=“text/css” href="mystyle.css">
</head>
For implementing this method, you need to first create the file mystyle.css and define your styles in it. This
method is also called linking.
Example:

/*mystyle.css*/ <!--external_style_sheet.htm-->
h1 <html>
{
font-weight:normal; <head>
font-size:16pt; <title>Style sheets by LINKING</title>
color:red <link rel="stylesheet" type="text/css" href=”mystyle.css”>
} </head>
p
{ <body>
font-weight:bold; <h1>I am formatted with a linked style sheet</h1>
text-align:center; <p>Me too!</p>
font-family:"sans serif";
</body>
color:blue
} </html>

2. Internal Style Sheet


An internal style sheet should be used when a single document has a unique style. Changing the
style sheet modifies only the document that contains it. You define internal styles in the head
section with the <style> tag.
<head>
<style type="text/css">
body {background-color: red}
p {margin-left: 20px}
</style>
</head>
This method is also called embedding.
3. Inline Style Sheet
The styles used within the tag are known as Inline styles.
E.g. <div style=“background-color: green;”>
<h2>Hello Friends!
<strong>How are you?</strong>
</h2>
</div>
CSS Background properties:
CSS Background properties define the background effects of an element. The background properties allow
you to control the background color of an element, set an image as the background, repeat a background
image vertically or horizontally, and position an image on a page.
1. Background image:

<!--background_image.gif-->
<html>
<head>
<style type="text/css">
body
{
background-image: url("cat.gif") ;/*image location*/
background-repeat: repeat-y ; /*image shown vertically*/
background-repeat:no-repeat; /*single image will be shown*/
background-position:center ; /*image aligned center*/
background-attachment: fixed; /*image does not move while scrolling*/
background-attachment: scroll; /*image moves while scrolling (default)*/
}
</style>
</head>
<body>
</body>
</html>
2. Background Colour:

<html>
<head>
<style type="text/css">
body {background-color: yellow}
h1 {background-color: #00ff00; width: 250px}
h2 {background-color: transparent}
p {background-color: rgb(250,0,255);width: 400px}
</style>
</head>
<body>
<h1>This is header 1</h1>
<h2>This is header 2</h2>
<p>This is a paragraph</p>
</body>
</html>
CSS Text Properties:

Text properties allow you to control the appearance of text. It is possible to change the color of a text,
increase or decrease the space between characters in a text, align a text, decorate a text, indent the first line in
a text, and more.
This example demonstrates how to set the color of the text and how to increase or decrease the space
between characters and many more.
<--textcss.htm-->
<html>
<head>
<style type="text/css">
h1 {color: red;} /*text color of h1 tag’s content is red*/
h2 {direction: rtl;} /* right to left placement of text (by default left to right)*/
h3 {letter-spacing: -3px; color: #dda0dd;} /*negative spacing among letters in a sentence*/
h4 {letter-spacing: 0.5cm; color: rgb(0,0,255);} /*spacing 0.5cm among letters in a sentence*/
h5{text-align: center; text-decoration: line-through;} /*text aligned to center and deprecated text*/
.indent {text-indent: 10%;} /*like margins in first line of paragraph*/
.trans {text-transform: capitalize;} /*First letter of Each word of a sentence is capital*/
.space {word-spacing: 1cm;} /*space among words is 1 cm*/
</style>
</head>
<body>
<h1>This is header 1</h1>
<h2>This is header 2</h2>
<h3>This is header 3</h3>
<h4>This is header 4</h4>
<h5>This is header 5</h5>
<p class="indent">I am bla bla bla.I am bla bla bla.I am bla bla bla.I am bla bla bla.I am bla bla
bla.I am bla bla bla.I am bla bla bla.I am bla bla bla.I am bla bla bla.I am bla bla bla.I am bla bla
bla.I am bla bla bla.I am bla bla bla.I am bla bla bla.I am bla bla bla.I am bla bla bla.I am bla bla
bla.I am bla bla bla.I am bla bla bla.I am bla bla bla.I am bla bla bla.I am bla bla bla.I am bla bla
bla. I am bla bla bla.
</p>
<p class="trans">the text is transformed to capital.</p>
<p class="space">Check the spaces between words.</p>
</body>
</html>

CSS Font Properties:

The Font properties allow you to change the font family, boldness, size, and the style of a text.

Note: If a browser does not support a font that is specified, it will use a default font.

Example:

<!--font_css.htm-->
<html>
<head>
<style type="text/css">
h3 {font-family: times} /*times new roman font family*/
p {font-family: courier} /*courier font family*/
p.sansserif {font-family: sans-serif; color:green} /*sans-serif font family, color green*/
h1 {font-size: 150%;font-style: italic} /*italic font with 150% more than normal size*/
h2 {font-size: 130%;font-style: normal}
p {font-size: 100%;font-style: oblique} /* having a slanting direction or position*/
p.normal {font-variant: normal; color:green} /*variation of font is normal*/
p.small {font-variant: small-caps} /*small size but capital*/
p.normal {font-weight: normal}
p.thick {font-weight: bold}
p.thicker {font-weight: 900}
</style>
</head>
<body>
<h3>This is header 3</h3>
<p> This is a paragraph</p>
<p class="sansserif">This is a paragraph</p>
<h1>This is header 1</h1>
<h2>This is header 2</h2>
<p class="normal">
This is a paragraph</p>
<p class="small">
This is a paragraph</p>
<p class="thick">This is a paragraph</p>
<p class="thicker">
This is a paragraph</p>
</body>
</html>

This example demonstrates how to use the shorthand property for setting all of the font
properties in one declaration.

<!--font_all_in_one.htm-->
<html>
<head>
<style type="text/css">
p{font: italic small-caps 900 12px arial} /*(font-style, font-variation, font-weight,
font-size, font-family)*/
</style>
</head>
<body>
<p>This is a paragraph</p>
</body>
</html>

CSS List: Changing styles of ordered and unordered lists using css.

The List properties allow you to change between different list-item markers, set an image as a list-item
marker, and set where to place a list-item marker. There is a property list-style-type which is used to change
the list items.

Unordered List:

Example:

<!--css_list.htm-->
<html>
<head>
<style type="text/css">
ul.disc{list-style-type: disc}
ul.circle {list-style-type: circle}
ul.square {list-style-type: square}
ul.none {list-style-type: none}
</style>
</head>
<body>
<ul class="disc">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
<ul class="circle">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
<ul class="square">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
<ul class="none">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
</body>
</html>
Ordered List:

<!--list_css.htm-->
<html>
<head>
<style type="text/css">
ol.decimal {list-style-type: decimal}
ol.lroman {list-style-type: lower-roman}
ol.uroman {list-style-type: upper-roman}
ol.lalpha {list-style-type: lower-alpha}
ol.ualpha {list-style-type: upper-alpha}
</style>
</head>
<body>
<ol class="decimal">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ol>
<ol class="lroman">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ol>
<ol class="uroman">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ol>
<ol class="lalpha">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ol>
<ol class="ualpha">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ol>
</body>
</html>
This example demonstrates how to set an image as the list-item marker

<!--css_list_image.htm-->
<html>
<head>
<style type="text/css">
ul {list-style-image: url("arrow.gif")}
</style>
</head>
<body>
<p><b>Note:</b> Netscape 4 does not support the "list-style-image" property.</p>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
</body>
</html>
Position The List Item Markers
The list-style-position property specifies the position of the list-item markers (bullet points). "list-
style-position: outside;" means that the bullet points will be outside the list item. This is default."list-
style-position: inside;" means that the bullet points will be inside the list item.
Example:
<html>
<body>
<style>
.a {
list-style-position: inside;
}
.b {
list-style-position: outside;
}
li {
margin: 5px;
border: 1px solid green;
}
</style>
</body>
<ul class="a">
<li>I am inside the border line.</li>
<li>I am inside the border line.</li>
<li>I am inside the border line.</li>
<li>I am inside the border line.</li>
<li>I am inside the border line.</li>
</ul>
<ul class="b">
<li>I am outside the border line.</li>
<li>I am outside the border line.</li>
<li>I am outside the border line.</li>
<li>I am outside the border line.</li>
<li>I am outside the border line.</li>
</ul>
<ol class="a">
<li>I am inside the border line.</li>
<li>I am inside the border line.</li>
<li>I am inside the border line.</li>
<li>I am inside the border line.</li>
<li>I am inside the border line.</li>
</ol>
<ol class="b">
<li>I am outside the border line.</li>
<li>I am outside the border line.</li>
<li>I am outside the border line.</li>
<li>I am outside the border line.</li>
<li>I am outside the border line.</li>
</ol>
</html>
Styling table in css/html

Border:

table, th, td {
border: 1px solid black;
}
Full width table:
table {
width: 100%;
}
Double borders:
table, td, th{
border: 1px solid black;
}
Collapse double borders into a single using border-collapse property.
table {
border-collapse: collapse;
}
Table width and height:

table {
width: 100%;
}
th {
height: 70px;
}
td {
text-align: center; /*aligning the text inside td tag center*/
}
Hoverable table:
tr:hover {background-color: #f5f5f5;}
Striped tables:
tr:nth-child(even) {background-color: #f2f2f2;} /*even tr tags background-color.*/
CSS Box Model
CSS Box model:

The CSS box model is essentially a box that wraps around every HTML element. It consists of:
margins, borders, padding, and the actual content. The image below illustrates the box model:
Remember every html elements are box and can be managed by using Box Model.

We can see the css box model in Computed tab.

Explanation of the different parts:


 Content - The content of the box, where text and images appear.
 Padding - Clears an area around the content. The padding is transparent.
 Border - A border that goes around the padding and content.
 Margin - Clears an area outside the border. The margin is transparent.
The box model allows us to add a border around elements, and to define space between elements.
Example
Demonstration of the box model:
div {
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}
If we create html div tag, then we can see the css box model in the inspect section, from where we
can manage the width, border, padding and margin of that div tag in a web page. (I must recommend
you all to do this now).

Normal Flow Box Layout: Basic Box Layout

Normal flow is a positioning of html elements one after another. If we put any <div> element and
after <div> if we put any <p> tag then there is a normal flow of these elements without colliding or
overlapping eachother.

Normal flow is the layout of the HTML elements in a Web page, when no positioning properties
are specified or (position:static i.e. default) is specified. All the elements inside of a webpage are
described in 2 categories.

There are two types of elements inside a webpage. (1) Block elements and (2) Inline elements.

(1) Block elements

Block elements in html such as <div>, <p>, <table>, <ul> elements are block level elements, having
display property by default display:block.

These elements‘ box model, generate line break (new line) both before and after their appearance
when they appear in the normal flow (CSS).

The block level elements in the normal flow stacks vertically one above another. Normally last
goes to the bottom most position.

If the width of the Block level elements like (<div>, <p>, <table>, <ul>) are not specified they takes
the whole width of the container.

Example
<div id="box1">Red div element</div>
<div id="box2">Blue div element</div>
Two DIVs are in normal flow, taken full width of container.

Red div

Blue div

When two div (block elements) are in normal flow and placed vertically one above another then their
common margin collapse or merge. But this does not arise when they are placed side by side.
(2) Inline elements
E.g <SPAN>, <B>,<strong>,<I> tags /elements. Inline elemets are placed side by side horizontally
unlike block elemets. These elements (element boxes, every element is considered as rectangular
box) donot generate line breaks.

Normally inline elements reside in a block level container or inside a block level element and they
appear side by side in normal flow. If they reach the right most wall of container then the inline
elements (i.e their box model) wraps to next line within the container and stays horizontally.

Display Property

Changing display property of block & inline elements


Even block elements can be shown as inline elements by changing the display property to inline as
follows. Similarly inline elements can be shown as block elements.
Changing block level element‘s – display:inline
In the following figure RED and BLUE are two DIVs, but in their CSS property we have
mentioned display:inline, so they appear side by side. In normal flow & static positioning, block
level elements never appear side by side, rather one above another. But here the block level elements
are behaving as inline elements.
Example
<div style="width: 50px; height: 50px; background-color: red; color: white; display: inline">Inline
Div 1</div>
<div style="width: 50px; height: 50px; background-color: blue; color: white; display:
inline">Inline Div 2</div>
CSS Margins

• The CSS Margin properties define the space around elements.


• It is possible to use negative values to overlap content.
• The top, right, bottom, and left margin can be changed independently using separate properties.
A shorthand margin property can also be used to change all of the margins at once.
• Shorthand margin rule:
Margin: 20px 30px 40px 50px;

Left, Right, Top and Bottom Margins:


<!--margin_left.htm-->
<html>
<head>
<style type="text/css">
p.margin {margin-top: 2cm}
p.margin {margin-right: 4cm}
p.margin {margin-bottom: 6cm}
p.margin {margin-left: 3cm}
</style>
</head>
<body>
<p>
This is a paragraph This is a paragraph
This is a paragraph This is a paragraph
</p>
<p class="margin">
This is a paragraph with a left margin
This is a paragraph with a left margin
</p>
</body>
</html>

The margin property can have from one to four values.


• margin:25px 50px 75px 100px;
– top margin is 25px
– right margin is 50px
– bottom margin is 75px
– left margin is 100px
• margin:25px 50px 75px;
– top margin is 25px
– right and left margins are 50px
– bottom margin is 75px
• margin:25px 50px;
– top and bottom margins are 25px
– right and left margins are 50px
• margin:25px;
– all four margins are 25px

CSS Padding:

• The CSS Padding properties define the space between the element border and the element
content.

• Negative values are not allowed.

• The top, right, bottom, and left padding can be changed independently using separate properties.
A shorthand padding property is also created to control multiple sides at once.

Example:
<!--padding_left.htm-->
<html>
<head>
<style type="text/css">
td {padding-left: 2cm}
</style>
</head>
<body>
<table border="1">
<tr>
<td>
This is a table cell with a left padding
</td>
</tr>
</table>
</body>
</html>

CSS Positioning:

• The CSS position property allows you to control the positioning of an element in a document.
• The element must specify the position attribute (relative or absolute).
 left - the element's left position
 top - the element's top position
 visibility - specifies whether an element should be visible or hidden
 z-index - the element's stack order
position:relative

• The position:relative property positions an element relative to its current position.

• The following example positions the div element 10 pixels to the right from where it is normally
positioned:

div
{
position:relative;
left:10px;
}
position:absolute

• The position:absolute property positions an element from the margins of the window.

• The following example positions the div element 10 pixels to the right from the left-margin of
the window:

div
{
position:absolute;
left:10px;
}
Visibility:

• The visibility property determines if an element is visible or not.

• The visibility:visible property makes the element visible.

h1
{
visibility:visible;
}
• The visibility:hidden property makes the element invisible.

h1
{
visibility:hidden;
}
Z-index:
The z-index property is used to place an element "behind" another element. Default z-index is 0. The
higher number the higher priority. z-index: -1 has lower priority.
h1
{
z-index:1;
}
h2
{
z-index:2;
}
In the example above, if the h1 and h2 elements are positioned on top of each other, the h2 element
will be positioned on top of the h1 element.

float:

Any elements of html can be floated left, right and none.

Example:

<!DOCTYPE html>
<html>
<head>
<style>
.div1 {
background: red;
float: left;
}
.div2 {
background: yellow;
float:right;
}
.div3 {
background: green;
float:none;
}
</style>
</head>
<body>

<h2>floating next to eachother</h2>


<p>Three different division tags float next to eachother.</p>
<div class="div1">Div 1</div>
<div class="div2">Div 2</div>
<div class="div3">Div 3</div>
</body>
</html>
Create a login form as shown below;
CSS3 Borders, Box Shadows, Text Effects and shadow

CSS3 Borders

CSS Border Style


The border-style property specifies what kind of border to display.
The following values are allowed:
 dotted - Defines a dotted border
 dashed - Defines a dashed border
 solid - Defines a solid border
 double - Defines a double border
 groove - Defines a 3D grooved border. The effect depends on the border-color value
 ridge - Defines a 3D ridged border. The effect depends on the border-color value
 inset - Defines a 3D inset border. The effect depends on the border-color value
 outset - Defines a 3D outset border. The effect depends on the border-color value
 none - Defines no border
 hidden - Defines a hidden border
The border-style property can have from one to four values (for the top border, right border, bottom
border, and the left border).
Example
Demonstration of the different border styles:
p.dotted {border-style: dotted;}
p.dashed {border-style: dashed;}
p.solid {border-style: solid;}
p.double {border-style: double;}
p.groove {border-style: groove;}
p.ridge {border-style: ridge;}
p.inset {border-style: inset;}
p.outset {border-style: outset;}
p.none {border-style: none;}
p.hidden {border-style: hidden;}
p.mix {border-style: dotted dashed solid double;}

Border radius properties:

Border radius properties are used to round the corners of the border boxes. For examole;

<!DOCTYPE html>
<html>
<head>
<style>
#id1 {
border: 2px solid red;
padding: 10px;
border-radius: 25px;
}

#id2 {
border: 2px solid red;
padding: 10px;
border-radius: 50px 20px;
}
</style>
</head>
<body>
<h2>border-radius: 25px:</h2>
<div id="id1">
<p>The border-radius property defines the radius of the element's corners.</p>
</div>
<h2>border-radius: 50px 20px:</h2>
<div id="id2">
<p>If two values are set; the first one is for the top-left and bottom-right corner, the second
one for the top-right and bottom-left corner.</p>
</div>

</body>
</html>

Box Shadows and Text Shadows:

The text-shadow and box-shadow properties are used to implement a shadow effect in text and box
in html.

Example:

<!DOCTYPE html>
<html>
<head>
<style>
#id1 { border: 1px solid; padding: 10px; box-shadow: 5px 10px;}/*color inherited*/
#id2 { border: 1px solid; padding: 10px; box-shadow: 5px 10px #888888;}
#id3 { border: 1px solid; padding: 10px; box-shadow: 5px 10px red;}
h1 { color: white; text-shadow: 2px 2px 4px #000000;}
</style>
</head>
<body>
<h1>Box Shadows and Text Shadows</h1>
<div id="id1">
<p>A div element with a shadow. The first value is the horizontal offset and the
second value is the vertical offset. The shadow color will be inherited from the text
color.</p>
</div>
<div id="id2">
<p>You can also define the color of the shadow. Here the shadow color is grey.</p>
</div>
<div id="id3">
<p>A red shadow.</p>
</div>
</body>
</html>

CSS Text effects

Types of Text Effects:

o Text-overflow
o Word-wrap
o Word-break
o Writing-mode
p{
• p.test1 { word-wrap: break-word;
white-space: nowrap; }
p.test1 {
width: 200px;
word-break: keep-all;
border: 1px solid #000000; }
overflow: hidden;
text-overflow: clip; p.test2 {
} word-break: break-all;
p.test2 { }
white-space: nowrap; p.test1 {
writing-mode: horizontal-tb;
width: 200px;
}
border: 1px solid #000000;
overflow: hidden; span.test2 {
text-overflow: ellipsis; writing-mode: vertical-rl;
} }

p.test1:hover { p.test2 {
overflow: visible; writing-mode: vertical-rl;
} }

Basics of Responsive Web Designs; Media Queries

Media query is a CSS technique introduced in CSS3.

It uses the @media rule to include a block of CSS properties only if a certain condition is true.

• @media only screen and (max-width: 600px) {


body {
background-color: lightblue;
}
}

• Condition is:
– If the browser window is 600px or smaller, the background color will be lightblue:

What is Responsive Web Design?


Responsive web design is about creating web sites which automatically adjust themselves to look
good on all devices, from small phones to large desktops.

Introduction to Bootstrap

• Bootstrap is a free front-end framework for faster and easier web development

• Bootstrap includes HTML and CSS based design templates for typography, forms, buttons,
tables, navigation, modals, image carousels and many other, as well as optional JavaScript
plugins

• Bootstrap also gives you the ability to easily create responsive designs

Components of Bootstrap:

1. Input Group – arranging the components in a group


2. Jumbotron -
3. Modal – pop up box
4. Navbar – for displaying menu
5. Pagination - to display multiple items in a single page using pagination
6. Popovers – displaying above some elements
7. Progress – progress bar
8. Scrollspy – changing tabs according to the contents by scrolling
9. Spinners -
10. Tooltips – suggestions for tools or image
11. Alerts
12. Badges
13. Breadcrumb
14. Buttons
15. ButtonGroup
16. Card
17. Carousel - slider
18. Collapse – show/hide
19. Dropdowns - list shown by clicking
20. Forms

Implementations:

We will do some of the components of Bootstrap from getbootstrap.com.

Embedding Bootstrap in Html Document:

<!DOCTYPE html>
<html lang="en">

<head>
<title>Document</title>
<link rel="stylesheet" href="css/bootstrap-5.0.1-dist/css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap-5.0.1-dist/css/bootstrap.min.css">
</head>
<style>
p{
background-color: red;
}
</style>

<body>
<div class="container">
<div class="row">
<div class="col-md-8">
<p>I am a p tag</p>
</div>
<div class="col-md-4">
<p>I am a p tag</p>
</div>
<p>I am a p tag</p>
</div>
<div class="row">
<div class="col-md">iam col 4</div>
<div class="col-md"> iam col 4</div>
<div class="col-md"> aim col 4</div>
</div>
<div class="row"></div>
</div>
<script src="css/bootstrap-5.0.1-dist/bootstrap.min.js"></script>
<script src="css/jquery-3.6.0.js"></script>

</body>
</html>
Unit 4: Client Side Scripting with JavaScript (9 Hrs.)
Structure of JavaScript Program; Variables and Data Types; Statements: Expression, Keyword,
Block; Operators; Flow Controls, Looping, Functions; Popup Boxes: Alert, Confirm, Prompt;
Objects and properties; Constructors; Arrays; Built-in Objects: Window, String, Number, Boolean,
Date, Math, RegExp, Form, DOM; User Defined Objects; Event Handling and Form Validation,
Error Handling, Handling Cookies, jQuery Syntax; jQuery Selectors, Events and Effects;
Introduction to JSON

4.1 Introduction to JavaScript:


JavaScript is a lightweight (can be embedded to any language, asp, jsp, php, etc.), object-based
programming language that supports the development of both client and server components of Web-
based applications. Web browser interprets JavaScript codes and shows output accordingly. On the
client side, it can be used to write programs that are executed by a Web browser within the context
of a Web Page. On the Server side, it can be used to write Web server programs that can process
information submitted by a Web browser and then update the browser's display accordingly.

Note: JavaScript was invented by Brendan Eich.

Need for JavaScript:

HTML is a specialized language for formatting pages and creating hyperlinks. It has no resources for
validating contents and has no structural commands to allow repetitive execution of parts of a
program.

If we create a form to receive data from user, the HTML simply shows the fields and accepts entry.
We cannot check for invalid entries and take action. Such a page or form is called static form. There
is a need to evaluate the contents of all the field types and return an error of warning i.e. to make a
page dynamic. For this task, several scripting languages are used of which JavaScript is widely used.
Hence, to modify the page according to the will of the user, JavaScript is used as it is also supported
by most browsers.

Structure of JavaScript:
JavaScript is an interpreted language means it does not need any compiler to be executed like other
languages like C, C++, java, etc.

The following is the structure of a JavaScript embedded in any html documents.

<html>

<head><title>JavaScript Strucutre</title></head>

<body>

<h2>Javascript Demonstration</h2>
</body>

<script language= “javascript” type=”text/javascript”><!—optional in html5

document.write(“This content is displayed inside the body tag of html document”);

alert(“This content is pop-up above the body tag of html document”);

</script>

</html>

In above structure, it is obviously seen that <script> tag is used to include any JavaScript code in
html document, which shows <script> is also a html tag that helps to embed JavaScript code
similarly as <style> tags are sued to include css to any html documents.

Multiple <script> tags can be include to any html document according to the need of a user. This is
done just to segregate the code otherwise it makes no sense in the context of execution of JS code in
a single <script> tag.

Working with JavaScript

There are two ways to include JavaScript in your web program:


1. Embedding the JavaScript code wholly within the document.
Embedding the JavaScript code: JavaScript statements can be included in HTML documents
by enclosing the statements between an opening <script> and closing</script> tag. Within
the opening tag, the language attribute is set to "JavaScript" to identify the script as being
JavaScript.
The script tag may be placed in either the head or the body of an HTML document. In many
cases, it is better to place the script tag in the head of the document to ensure that all
JavaScript definitions have been made before the body of the document is displayed but this
may increase page load time.
2. Creating the external file with the JavaScript code
Loading an external file: Using an external file is very simple: we have to just add the
JavaScript file address to the <SCRIPT> command line by means of the SRC attribute.
<html>
<head>
<title> Using JavaScript</title>
</head>
<body> … </body>
<script language=“JavaScript” src=“code.js”>
</html>
Example:
show.js
<html> document.write("Hello Nepal!")
<head> document.write("MyNepal,My
<title>External JavaScript</title> Pride.")
</head>
<body>
<script language="JavaScript" SRC="show.js">
/* document.write("Hello Nepal!")*/
// document.write("My Nepal,My Pride.")
</script>
</body>
</html>

4.2 Variables and Data Types


Unlike Java and some other programming languages, JavaScript does not require you to specify the
type (int, float, char etc.) of data contained in a variable.

In fact, the same variable may be used to contain a variety of different values, such as the text string,
integer, floating-point value or logical value. JavaScript frees you from having to explicitly specify
the type of data contained in variable and from having to convert from one data type to another
automatically.

JavaScript supports following data types: Number - Consists of integer and floating-point number.
Boolean - Consists of logical values true and false. String - Consists of string values. Null - Consists
of a single value, null.

JavaScript variables are "containers" for storing information. To declare a variable in JavaScript,
use the var (optional) keyword: e.g. var carname; After the declaration, the variable is empty (it
has no value).

 To assign a value to the variable, use the equal sign: e.g. carname="Volvo";
 We can declare many variables in one statement as: e.g. var name="Doe", age=30,
job="carpenter";
 Variables can have short names (like x and y) or more descriptive names (age, sum,
totalvolume). Some rules are:
 Variable names must begin with a letter
 Variable names can also begin with $ and _ (but not used often)
 Variable names are case-sensitive (y andY are different variables)
Note:―semicolon‖is optional in JavaScript.
Local JavaScript Variables/ Function Scope Variables:

A variable declared within a JavaScript function becomes LOCAL and can only be accessed within
that function. (the variable has local scope).You can have local variables with the same name in
different functions, because local variables are only recognized by the function in which they are
declared. Local variables are destroyed when you exit the function.

Global JavaScript Variables:

Variables declared outside a function becomes GLOBAL, and all scripts and functions on the web
page can access it. Global variables are destroyed when you close the page. If you declare a variable,
without using "var", the variable always becomes GLOBAL

Assigning Values to Undeclared JavaScript Variables: If you assign values to variables that have not
yet been declared, the variables will automatically be declared as global variables. For example, x=5;
carname="Volvo"; will declare the variables x and carname as global variables (if they don't already
exist).

JavaScript Block Scope

Variables declared with the var keyword cannot have Block Scope. Variables declared inside a
block { } can be accessed from outside the block. But using let rather than var keyword at the time
of variable declaration inside { } block, it restricts any variables to be used outside the block. Hence,
the let variables has scope only inside the { } block.

Example: using var keyword


{
var name = harendra;
}
//here name can be accessed here i.e. outside the { } block.

Example: using let keyword

let atmPin=1111;

//atmPin has no access outside the { } block

Implementation:

<!DOCTYPE html>
<html>
<body>
<h2>Declaring a Variable Using var</h2>
<p id="testId"></p>

<script>
var x = 10;
var y = 100;
// Here x is 10
//Here y is 100
{
let x = 20;
var y=50;
// Here x is 20
//Here y is 50
}
// Here x is 10
//Here y is 50
document.getElementById("testId").innerHTML = x+" and "+y;
</script>
</body>
</html>

Variable Declaration:
<html>
<head>
<title>Declaring Variables</title>
</head>
<script language="JavaScript">
var $motto = "<H1>My Nepal,My Pride.</H1>";
var _text = "<P>Welcome to <B><U><I>Himalayan Country</I></U></B>.</P>";
abc = "JustTesting";
</script>
<body>
<script language="JavaScript">
document.write($motto)
document.write(_text)
document.write(abc)
</script>
</body>
</html>

Statements: Expression, Keyword, Block


JavaScript statements are composed of: Values, Operators, Expressions, Keywords, and Comments.
And, semicolon separates the statements. For example;
<script>
var x, y, z; //first statement
x=10; //second statement
y=30;//third statement
z=x+y;//fourth statement or expression
</script>

Blocks:
JavaScript statements can be grouped together in code blocks, inside curly brackets {...}. The
purpose of code blocks is to define statements to be executed together. There is a one place where
we will find statements grouped together in blocks, i.e. in JavaScript functions as sown below.
<html>
<body>
<form onsubmit=‖addIntegers()‖>
First number: <input type =‖text‖ name=‖fnum‖ id=‖firstnum‖>
Second number: <input type =‖text‖ name=‖snum‖ id=‖secondnum‖>
<input type=‖submit‖ value=‖Addition‖>
</form>
<p id =‖finalvalue‖></p>
</body>
</html>
<script>
function addIntegers(){
var x = document.getElementById(―firstnum‖).value;
var y = document.getElementById(―secondnum‖).value;
var z=x+y;
document.getElementById(―finalvalue‖).innerHTML=z;
}
</script>

Operators:
Unary Operators
++ - Increment current value by 1
-- - Decrement current value by 1
Types of Unary Operators
a++ - Post Increment
++a - Pre Increment
a-- - Post Decrement
--a - Pre Decrement
Binary Operators
+ - Addition
- - Subtraction
/ - Division
* - Multiplication
% - Modulus
Logical Operators
&& - Logical AND
|| - Logical OR
! - Logical NOT

Relational Operators
== - Equal
= = = - Strictly Equal
!= - Not Equal
!= = - Strictly Not Equal
< - Less Than
<= - Less Than or Equal
> - Greater Than >= - Greater Than or Equal

Note: The equal (= =) and not equal (!=) operators perform type conversions before testing for
equality. For instance, "5" = = 5 evaluates to 'true'. The strictly equal (= = =) and strictly not equal
(!= =) operators do not perform type conversions before testing for equality. For instance, "5" = = =
5 evaluates to 'false' and "5" != = 5 evaluates 'true'.

Assignment Operators
= - Assign right value to left variable
+= - Assign right value to left variable with incrementing right value by left value.
-= - Assign right value to left variable with decrementing right value by left value.
* = - Assign right value to left variable with multiplying right value by left value.
/= - Assign right value to left variable with dividing right value by left value.
% = - Assign right value to left variable with taking modulus of right value by left value.

Conditional Operator: A conditional operator assigns a value to a variable based on some


condition.
Syntax:
variablename=(condition)?value1:value2
Example:
If the variable age is a value below 18, the value of the variable voteable will be "Too young‖,
otherwise the value of voteable will be "Old enough":
voteable=(age<18)?"Too Young":"old enough";

4.3 Control Structures/Statements:

Two types:
● Decision-making statements
● Loops

Decision Making Statements:


In JavaScript we have the following conditional statements:
✔ if statement - use this statement to execute some code only if a specified condition is true
✔ if...else statement - use this statement to execute some code if the condition is true and another
code if the condition is false
✔ if...else if....else statement - use this statement to select one of many blocks of code to be
executed
✔ switch statement - use this statement to select one of many blocks of code to be executed

E.g. if---else—condition statement


<html>
<head>
<title>JavaScript:if else</title>
</head>
<body>
<script language="JavaScript">
var My_Age = 10
if (My_Age >= 18)
document.write("You can vote in this election.")
else
document.write("Sorry, you cannot vote in this election.")
</script>
</body>
</html>

Switch Statement:
<html>
<head>
<title>JavaScript:switch</title>
</head>
<script language="JavaScript">
my_color = 2
switch (my_color) {
case 1: document.write("<body bgcolor=" + "#ff0000>" + "Red" + "</body>")
break
case 2: document.write("<body bgcolor=" + "#00ff00>" + "Green" + "</body>")
break
case 3: document.write("<body bgcolor=" + "#0000ff>" + "Blue" + "</body>")
break
}
</script>

Loops:
JavaScript supports different kinds of loops:
● for - loops through a block of code a number of times
● for/in - loops through the properties of an object
● while - loops through a block of code while a specified condition is true
● do/while - also loops through a block of code while a specified condition is true

For loop:

<html>
<head>
<title>JavaScript: for loop</title>
</head>
<body>
<script language="JavaScript">
for (i = 1; i < 7; i++)
document.write("<H" + i + ">This is a level " + i +"heading."+"</H"+i+" > ")
</script>
</body>
</html>
For –in loop

<html>
<body>
<script type="text/javascript">
var person = { fname: "John", lname: "Doe", age: 25 };
//creation of object person
for (x in person) {
document.write(person[x] + " ");
}
</script>
</body>
</html>

While Loop:

<html>

<head>
<title>JavaScript:while</title>
</head>
<body>
<script language="JavaScript">
i=1
document.write("<H4>S.No.</H4>")
while (i <= 50) {
document
.write(i)
document
.write("<BR>")
++i
}
</script>
</body>
</html>

Do-While Loop

<html>
<head>
<title>JavaScript:do-while</title>
</head>

<body>
<script language="JavaScript">
i=1
document
.write("<H4>S.No.</H4 > ")
do {
document
.write(i)
document
.write("<BR>")
++i
} while (i <= 50)
</script>
</body>
</html>

Break and Continue Statements:

● The break statement breaks the loop and continues executing the code after the loop (if any). It is
also used to "jump out" of a switch() statement.
● The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.

E.g.
<html>
<head>
<title>JavaScript: break and continue</title>
</head>

<body>
<script language="JavaScript">
document.write("<B>Serial Numbers: </B>")
for (i = 1; i < 50; i++) {
document.write(i + " ")
if (i % 20 == 0) break
}
document.write("<BR><B>Interval Numbers: </B>")
for (i = 1; i <= 50; i++) {
if (i % 5 != 0) continue
document.write(i + " ")
}
</script>
</body>
</html>

Output:
Serial Numbers: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Interval Numbers: 5 10 15 20 25 30 35 40 45 50
Array and for each loop:

Array:
JavaScript arrays are used to store multiple values in a single variable.

E.g.
var cars = ["Saab", "Volvo", "BMW"];
or
var cars = [
"Saab",
"Volvo",
"BMW"
];
or
var cars = new Array("Saab", "Volvo", "BMW");

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.

Accessing the elements of an array:


var name = cars[0];
or using tag id of html;
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
Here, you can display the accessed array item to a particular part of a html page.

Note: Array indexes start with 0.

[0] is the first element. [1] is the second element.

Changing an array element:


var cars = ["Toyota", "Suzuki", "BMW"];
cars[0] = "Opel";
document.getElementById("demo").innerHTML = cars[0];
Accessing full array:
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = 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:
var person = ["John", "Doe", 46];

Object
var person = {firstName:"John", lastName:"Doe", age:46};

Accessed using person.firstName, person.lastName and so on.

for each loop in javascript:

var fruits = ["apple", "orange", "cherry"];


fruits.forEach(myFunction);

function myFunction(item, index) {


document.getElementById("demo").innerHTML += index + ":" + item + "<br>";
}

4.4 JavaScript Function Syntax

A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}

Syntax:
function name(parameter1, parameter2, parameter3) {
// code to be executed
}

 Function parameters are listed inside the parentheses () in the function definition.
 Function arguments are the values received by the function when it is invoked.
 Inside the function, the arguments (the parameters) behave as local variables.

Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:

● When an event occurs (when a user clicks a button)


● When it is invoked (called) from JavaScript code
● Automatically (self invoked)
Function Return

When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after the
invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":

E.g.
<html>
<body>

<h2>JavaScript Functions</h2>

<p>This example calls a function which performs a calculation and returns the result:</p>

<p id="demo"></p>

<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;

function myFunction(a, b) {
return a * b;
}
</script>
</body>
</html>

Why Functions?

You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce different results.
E.g.
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;

Function can be used as variable values:


var x = toCelsius(77);
var text = "The temperature is " + x + " Celsius";
or
var text = "The temperature is " + toCelsius(77) + " Celsius";
JavaScript Popup Boxes
JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
Alert Box
An alert box is often used if you want to make sure information comes through to the user.
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
window.alert("sometext");
The window.alert() method can be written without the window prefix.
Example
alert("I am an alert box!");

Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
Syntax
window.confirm("sometext");
The window.confirm() method can be written without the window prefix.

Prompt Box
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after
entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns
null.
Syntax
window.prompt("sometext","defaultText");
The window.prompt() method can be written without the window prefix.
Example
var person = prompt("Please enter your name", "Harry Potter");

if (person == null || person == "") {


txt = "User cancelled the prompt.";
} else {
txt = "Hello " + person + "! How are you today?";
}

<!--prompt test.html-->
<!DOCTYPE html>
<html>
<head><title>JavaScript PROMPT Testing</title></head>
<body>
<script type="text/javascript">
var name=prompt("Please enter your name","Harendra Raj Bist");
var x="";
if (name === "")
/* "" for no input value and null for return value of prompt */
{
document.write("You didn't input any name and clicked OK");
}
else if( (name+".") === "null.")
{
document.write("You clicked CANCEL");
}
else
{
x="Hello! " + name + " .How are you today?";
document.write(x);
}
</script>
</body>
</html>
Line Breaks
To display line breaks inside a popup box, use a back-slash followed by the character n.
Example
alert("Hello\nHow are you?");

4.5 Object Properties and Constructors in JavaScript

Object.js
class Company {//class
//default constructor is already here and properties are declared on the basis of object
}
const microsoft = new Company();//an object of a class
microsoft.name = "Microsoft Corporation"; // Add a name property with a value to our company
document.write(microsoft.name); // Print it on the page

Object.html
<body>
<script src="object.js"></script>
</body>
Modify the code of Object.js as follows

class Company {

constructor() {
this.name = "Company name";
this.address = "New York City";
}
}
const microsoft = new Company();
const google = new Company();
document.write(microsoft.name); // Print company names
document.write('<br />');
document.write(google.name);

Output will be the same name for both companies.

Solution for above problem is using parameterized constructor as below;

class Company {

constructor(name, address) {
this.name = name
this.address = address
}
}
const c1 = new Company(“Wai-wai”,”Texas”);
const c2 = new Company(“Ruslan”,”Russia”);
document.write(c1.name); // Print company names
document.write('<br />');
document.write(c2.name);

As Javascript supports functions so we can use functions for different purposes:

Complete example to demonstrate the class object properties and constructor:


class Student {
students = [];
constructor(id, name, address, email) {
this.id = id;
this.name = name;
this.address = address;
this.email = email;
}

addStudent() {
const id = prompt("Enter student id:")
const name = prompt("Enter the student's name");
const address = prompt("Enter student address");
const email = prompt("Enter student email");
const student = new Student(id, name, address, email);
this.students.push(student); // Add new student to the array
}
printStudentInfo() {
document.write("<h3>Students</h3>");
const list = document.createElement("ul"); // Create the list as an HTML element
for (const student of this.students) { // Fill it with data
list.innerHTML += `<li><strong>Id</strong>: ${student.id}</li>`;
list.innerHTML += `<li><strong>Name</strong>: ${student.name}</li>`;
list.innerHTML += `<li><strong>Address</strong>: ${student.address}</li>`;
list.innerHTML += `<li><strong>Email</strong>: ${student.email}</li><br>`;
}
document.body.appendChild(list); // Append the element to the page body
}
}
const stobj = new Student(1, "harendra", "naikap", "[email protected]");
document.write("<ul>");
document.write("<li><strong>Id</strong>:" + stobj.id + "</li>");
document.write("<li><strong>Name</strong>:" + stobj.name + "</li>");
document.write("<li><strong>Address</strong>:" + stobj.address + "</li>");
document.write("<li><strong>Email</strong>:" + stobj.email + "</li>");
document.write("</ul>");
stobj.addStudent();
stobj.printStudentInfo();

Note: const is used for constant reference, means no values will be reassigned if any variable, object
reference is declared with const.

JavaScript Constructors:
The constructor() method is a special method for creating and initializing objects created within a
class.
The constructor() method is called automatically when a class is initiated, and it has to have the
exact name "constructor", in fact, if you do not have a constructor method, JavaScript will add an
invisible and empty constructor method.

Note: A class cannot have more than one constructor() method. This will throw a SyntaxError.
You can use the super() method to call the constructor of a parent class.

Example:
<!DOCTYPE html>
<html>

<body>
<h2>JavaScript Object Constructors</h2>
<p id="infoId"></p>
<script>
// Constructor function for Student objects
function Student(id, name, age, email) {
this.id = id;
this.name = name;
this.age = age;
this.email = email;
}

// Create a Student object


const stud = new Student(101, "Harendra", 30, "[email protected]");

// Display Info
document.getElementById("infoId").innerHTML = "<h3>My name is " + stud.name +
"." + " roll no. is " + stud.id + " and email is: " + stud.email + "</h3>";
</script>
</body>
</html>

4.6 Arrays
JavaScript arrays are used to store multiple values in a single variable.
E.g.
var cars = ["Saab", "Volvo", "BMW"];
or
var cars = [
"Saab",
"Volvo",
"BMW"
];
or
var cars = new Array("Saab", "Volvo", "BMW");

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.
Accessing the elements of an array:
var name = cars[0];
or using tag id of html;
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
Here, you can display the accessed array item to a particular part of a html page.

Note: Array indexes start with 0.

[0] is the first element. [1] is the second element.

Changing an array element:


var cars = ["Toyota", "Suzuki", "BMW"];
cars[0] = "Opel";
document.getElementById("demo").innerHTML = cars[0];

Accessing full array:


var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = 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:

var person = ["John", "Doe", 46];

Object
var person = {firstName:"John", lastName:"Doe", age:46};
Accessed using person.firstName, person.lastName and so on.

Array Elements Can Be Objects

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:

myArray[0] = Date.now;

myArray[1] = myFunction;

myArray[2] = myCars;

Array Properties and Methods


The real strength of JavaScript arrays are the built-in array properties and methods:
var x = cars.length; // The length property returns the number of elements
var y = cars.sort(); // The sort() method sorts arrays

The length property:

The length property of an array returns the no of elements that are stored in an array.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length is a property and length of fruits is 4
fruits.sort(); // sort() is a function and sorts the array elements alphabetically

e.g.
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>The length property returns the length of an array.</p>
<p id="demo"></p>
<p id="sort"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("sort").innerHTML = fruits.sort();
document.getElementById("demo").innerHTML = fruits.length;
</script>
</body>
</html>

Looping Array Elements:


e.g.
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>The best way to loop through an array is using a standard for loop:</p>
<p id="demo"></p>

<script>
var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

for each loop in javascript:


var fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);

function myFunction(item, index) {


document.getElementById("demo").innerHTML += index + ":" + item + "<br>";
}

Note: for each loop is used to display the elements of an array according to indexes. The forEach()
method calls a function once for each element in an array, in order.
The function is not executed for array elements without values.

e.g.
var sum = 0;
var numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);

function myFunction(item) {
sum += item;
document.getElementById("demo").innerHTML = sum;
}

Note: foreach can take function as argument and you can perform the task accordingly.

4.7 Built-in Objects: Window, String, Number, Boolean, Date, Math, RegExp,
Form
 Booleans can be objects (if defined with the new keyword)
 Numbers can be objects (if defined with the new keyword)
 Strings can be objects (if defined with the new keyword)
 Dates are always objects
 Maths are always objects
 Regular expressions are always objects
 Arrays are always objects
 Functions are always objects
 Objects are always objects

Built in objects:
 Built-in objects are not related to any Window or DOM object model.
 These objects are used for simple data processing in the JavaScript.

1. The Window Object


The window object is supported by all browsers. It represents the browser's window.

All global JavaScript objects, functions, and variables automatically become members of the
window object.
Global variables are properties of the window object.
Global functions are methods of the window object.
Even the document object (of the HTML DOM) is a property of the window object:

window.document.getElementById("header");
is the same as:
document.getElementById("header");

Two properties can be used to determine the size of the browser window.
Both properties return the sizes in pixels:
 window.innerHeight - the inner height of the browser window (in pixels)
 window.innerWidth - the inner width of the browser window (in pixels)

A practical JavaScript solution (covering all browsers):

<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>

<script>
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

var x = document.getElementById("demo");
x.innerHTML = "Browser inner window width: " + w + ", height: " + h + ".";
</script>
</body>
</html>

Other Window Methods


Some other methods:
 window.open() - open a new window
 window.close() - close the current window
 window.moveTo() - move the current window
 window.resizeTo() - resize the current window

2. Math Object
 Math object is a built-in static object.
 It is used for performing complex math operations.
Math Description
Property
SQRT2 Returns square root of 2.
PI Returns Π value.
E\ Returns Euler's Constant.
LN2 Returns natural logarithm of 2.
LN10 Returns natural logarithm of 10.
LOG2E Returns base 2 logarithm of E.
LOG10E Returns 10 logarithm of E.

Math Methods

Methods Description
abs() Returns the absolute value of a number.
acos() Returns the arccosine (in radians) of a number.
ceil() Returns the smallest integer greater than or equal to a number.
cos() Returns cosine of a number.
floor() Returns the largest integer less than or equal to a number.
log() Returns the natural logarithm (base E) of a number.
max() Returns the largest of zero or more numbers.
min() Returns the smallest of zero or more numbers.
pow() Returns base to the exponent power, that is base exponent.

Example:
<html>
<head>
<title>JavaScript Math Object Properties</title>
</head>
<body>
<script type="text/javascript">
var value1 = Math.E
document.write("E Value is :" + value1 + "<br>");

var value2 = Math.LN2


document.write("LN2 Value is :" + value2 + "<br>");

var value3 = Math.LN10


document.write("LN10 Value is :" + value3 + "<br>");

var value4 = Math.PI


document.write("PI Value is :" + value4 + "<br>");
</script>
</body>
</html>

3. Date Object
 Date is a data type.
 Date object manipulates date and time.
 Date() constructor takes no arguments.
 Date object allows you to get and set the year, month, day, hour, minute, second and millisecond
fields.

Syntax:
var variable_name = new Date();

Example:
var current_date = new Date();

Date Methods

Methods Description
Date() Returns current date and time.
getDate() Returns the day of the month.
getDay() Returns the day of the week.
getFullYear() Returns the year.
getHours() Returns the hour.
getMinutes() Returns the minutes.
getSeconds() Returns the seconds.
getMilliseconds() Returns the milliseconds.
getTime() Returns the number of milliseconds since January 1, 1970 at 12:00 AM.
getTimezoneOffset() Returns the timezone offset in minutes for the current locale.
getMonth() Returns the month.
setDate() Sets the day of the month.
setFullYear() Sets the full year.
setHours() Sets the hours.
setMinutes() Sets the minutes.
setSeconds() Sets the seconds.
setMilliseconds() Sets the milliseconds.
setTime() Sets the number of milliseconds since January 1, 1970 at 12:00 AM.
setMonth() Sets the month.
toDateString() Returns the date portion of the Date as a human-readable string.
toLocaleString() Returns the Date object as a string.
toGMTString() Returns the Date object as a string in GMT timezone.
valueOf() Returns the primitive value of a Date object.

Example:

<html>
<body>
<center>
<h2>Date Methods</h2>
<script type="text/javascript">
var d = new Date();
document.write("<b>Locale String:</b> " + d.toLocaleString()+"<br>");
document.write("<b>Hours:</b> " + d.getHours()+"<br>");
document.write("<b>Day:</b> " + d.getDay()+"<br>");
document.write("<b>Month:</b> " + d.getMonth()+"<br>");
document.write("<b>FullYear:</b> " + d.getFullYear()+"<br>");
document.write("<b>Minutes:</b> " + d.getMinutes()+"<br>");
</script>
</center>
</body>
</html>

4. String Object

 String objects are used to work with text.


 It works with a series of characters.
Syntax:
var variable_name = new String(string);

Example:
var s = new String(string);

String Methods
Methods Description
charAt() It returns the character at the specified index.
charCodeAt() It returns the ASCII code of the character at the specified position.
concat() It combines the text of two strings and returns a new string.
indexOf() It returns the index within the calling String object.
match() It is used to match a regular expression against a string.
replace() It is used to replace the matched substring with a new substring.
search() It executes the search for a match between a regular expression.
split() It splits a string object into an array of strings by separating the string into the substrings.
toLowerCase() It returns the calling string value converted lower case.
toUpperCase() Returns the calling string value converted to uppercase.

Example:

<html>
<body>
<center>
<script type="text/javascript">
var str = "CareerRide Info";
var s = str.split();
document.write("<b>Char At:</b> " + str.charAt(1)+"<br>");
document.write("<b>CharCode At:</b> " + str.charCodeAt(2)+"<br>");
document.write("<b>Index of:</b> " + str.indexOf("ide")+"<br>");
document.write("<b>Lower Case:</b> " + str.toLowerCase()+"<br>");
document.write("<b>Upper Case:</b> " + str.toUpperCase()+"<br>");
</script>
<center>
</body>
</html>
5. Number
Number is a primitive wrapper object used to represent and manipulate numbers like 37 or -
9.25.The Number constructor contains constants and methods for working with numbers. Values of
other types can be converted to numbers using the Number() function.

Literal Sytax:
123; //integer
123.0; //float
123==123.0; //true

Function syntax:
Number(‗123‘);
Number(‗123.0‘);
Number(‗123‘)==123; //true
Number(‗Hello‘); //NaN

Example:
biggestNum=Number.MAX_VALUE;
smallestNum=Number.MIN_VALUE;
finiteNum=Number.POSITIVE_INFINITY;
negInfiniteNum=Number.NEGATIVE.INFINITY;
notANum=Number.NaN;

Using Number() to convert Date to number


let date = new Date(―December 17, 1988 06:39:55‖);
document.write(Number(date));

6. Boolean
The Boolean object represents two values, either "true" or "false". If value parameter is omitted or
is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.

Syntax
Use the following syntax to create a boolean object.
var val = new Boolean(value);

Example:
Boolean(5>9);//false

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Booleans</h2>
<p>Display the value of Boolean:</p>
<p id="test"></p>
<p id="test1"></p>
<p id="test2"></p>
<script>
document.getElementById("test").innerHTML = Boolean(125> 115);
document.getElementById("test1").innerHTML = (10 < 9);
document.getElementById("test2").innerHTML = 20 > 19;

</script>
</body>
</html>

Everything with a value is True:


<html>
<body>
<h2>JavaScript Booleas</h2>
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"100 is " + Boolean(100) + "<br>" +
"3.14 is " + Boolean(3.14) + "<br>" +
"-15 is " + Boolean(-15) + "<br>" +
"Any (not empty) string is " + Boolean("Hello") + "<br>" +
"Even the string 'false' is " + Boolean('false') + "<br>" +
"Any expression (except zero) is " + Boolean(1 + 7 + 3.14);

//do additional task in class given below..


//but below statement is false
let x=0;or x=-0 or x=””; or let x or x=null or x=false or x=10/”hi”;
Boolean(x);//false

//Booleans can be object


let x = false;
let y = new Boolean(false);
// typeof x returns boolean
// typeof y returns object

//Booleans values can be equal


let x = false;
let y = new Boolean(false);
// (x == y) is true because x and y have equal values
//using=== operator
let x = false;
let y = new Boolean(false);
// (x === y) is false because x and y have different types
//comparing objects
let x = new Boolean(false);
let y = new Boolean(false);
//x==y returns false because objects cannot be compared
</script>
</body>
</html>

7. Regular Expression
A regular expression is a sequence of characters that forms a search pattern.
When you search for data in a text, you can use this search pattern to describe what you are searching
for.
A regular expression can be a single character, or a more complicated pattern.
Regular expressions can be used to perform all types of text search and text replace operations.

Regex object:
A regular expression is an object that describes a pattern of characters.
The JavaScript RegExp class represents regular expressions, and both String and RegExp define
methods that use regular expressions to perform powerful pattern-matching and search-and-replace
functions on text.

Syntax
A regular expression could be defined with the RegExp () constructor, as follows −
Object syntax:
var pattern = new RegExp(pattern, attributes);
or simply
literal syntax:
var pattern = /pattern/attributes;
Here is the description of the parameters −
 pattern − A string that specifies the pattern of the regular expression or another regular
expression.
 attributes − An optional string containing any of the "g", "i", and "m" attributes that specify
global, case-insensitive, and multi-line matches, respectively.
Brackets

Brackets ([]) have a special meaning when used in the context of regular expressions. They are used
to find a range of characters.
Sr.No. Expression & Description
1
[...]
Any one character between the brackets.
2
[^...]
Any one character not between the brackets.
3
[0-9]
It matches any decimal digit from 0 through 9.
4
[a-z]
It matches any character from lowercase a through lowercase z.
5
[A-Z]
It matches any character from uppercase A through uppercase Z.
6
[a-Z]
It matches any character from lowercase a through uppercase Z.
The ranges shown above are general; you could also use the range [0-3] to match any decimal digit
ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging
from b through v.

Quantifiers

The frequency or position of bracketed character sequences and single characters can be denoted by
a special character. Each special character has a specific connotation. The +, *, ?, and $ flags all
follow a character sequence.
Sr.No. Expression & Description

1
p+
It matches any string containing one or more p's.
2
p*
It matches any string containing zero or more p's.
3
p?
It matches any string containing at most one p.
4
p{N}
It matches any string containing a sequence of N p's
5
p{2,3}
It matches any string containing a sequence of two or three p's.
6
p{2, }
It matches any string containing a sequence of at least two p's.
7
p$
It matches any string with p at the end of it.
8
^p
It matches any string with p at the beginning of it.

Examples
Following examples explain more about matching characters.
Sr.No. Expression & Description

1
[^a-zA-Z]
It matches any string not containing any of the characters ranging
from a through z and A through Z.
2
p.p
It matches any string containing p, followed by any character, in turn followed by
another p.
3
^.{2}$
It matches any string containing exactly two characters.
4
<b>(.*)</b>
It matches any string enclosed within <b> and </b>.
5
p(hp)*
It matches any string containing a p followed by zero or more instances of the
sequence hp.

Literal characters

Sr.No. Character & Description

1
Alphanumeric
Itself
2
\0
The NUL character (\u0000)
3
\t
Tab (\u0009
4
\n
Newline (\u000A)
5
\v
Vertical tab (\u000B)
6
\f
Form feed (\u000C)
7
\r
Carriage return (\u000D)
8
\xnn
The Latin character specified by the hexadecimal number nn; for example, \x0A is the
same as \n
9
\uxxxx
The Unicode character specified by the hexadecimal number xxxx; for example, \u0009
is the same as \t
10
\cX
The control character ^X; for example, \cJ is equivalent to the newline character \n

RegExp Methods

Here is a list of the methods associated with RegExp along with their description.
Sr.No. Method & Description

1 exec()

Executes a search for a match in its string parameter.


2 test()
Tests for a match in its string parameter.
3 toSource()
Returns an object literal representing the specified object; you can use this value to
create a new object. May not work in some browsers.
4 toString()
Returns a string representing the specified object.

Examples:
test() method:
<script>
var str = "Hello";
var re = new RegExp("/hello/","i");
var result = re.test(str);
document.write(result)
</script>
exec() method
<!DOCTYPE html>
<html>
<body>

<script>
let url = 'https://vedascollege.edu.np';
// Creating regex object
let re = new RegExp(/[^.]+/);//rule is: [^.]+ means "one or more non-dot characters
let result = re.exec(url)[0];//return non dot characters

document.write(result+"</br>");

let result1 = re.exec(url)[0].substring(8);//return the sub string from 9th to last letter
document.write(result1);
</script>
</body>
</html>
toString() method:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to return the string value of the regular expression.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
function myFunction() {
var patt = new RegExp("Hello World", "g");
var res = patt.toString();
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
Output:
/Hello World/g

8. Forms
JavaScript Form Validation

HTML form validation can be done by JavaScript.

If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the form
from being submitted:

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>

<form name="myForm" action="/action_page.php" onsubmit="return validateForm()"


method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>

Automatic HTML Form Validation without JavaScript

<!DOCTYPE html>
<html>
<body>

<form action="/action_page.php" method="post">


<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>
<p>If you click submit, without filling out the text field,
your browser will display an error message.</p>
</body>
</html>

DOM
HTML DOM:
The HTML DOM defines the objects and properties of all HTML elements, and the methods to
access them.
 When a web page is loaded, the browser creates a Document Object Model of the page.
 The HTML DOM model is constructed as a tree of Objects.
 With a programmable object model, JavaScript gets all the power it needs to create dynamic
HTML:
a) JavaScript can change all the HTML elements in the page
b) JavaScript can change all the HTML attributes in the page
c) JavaScript can change all the CSS styles in the page
d) JavaScript can react to all the events in the page
HTML DOM Tree

JavaScript to change the elements of html:

To manipulate HTML elements, we have to find the html elements first. To do so, we can:
 Find HTML elements by id
 Find HTML elements by tag name
 Find HTML elements by class name
 The easiest and most common method to find HTML elements in the DOM is by using the
element id for which we use the getElementById method.
Example: var x=document.getElementById(“intro”);
will find the element with id=―intro‖. If the element is found, the method will return the element as
an object (in x). If the element is not found, x will contain null.
Next, to modify the content of an HTML element, use the innerHTML property.
Example: document.getElementById(“intro”).innerHTML=“some text”

Example:
<html>
<head><title>Manipulating HTML elements by using ID</title></head>
<body>
<h3>To change the text</h3>
<p id="intro">Watch Me</p>
<script>
var x=document.getElementById("intro");
x.innerHTML="I have changed";
</script>
<h3>To change the image</h3>
<img src="hukum_rani.gif" id="image">
<script>
var x = document.getElementById("image");
x.src = "hukum_raja.gif";
</script>
</body>
</html>
Changing HTML Elements
Property Description
element.innerHTML = new html Change the inner HTML of an element
content
element.attribute = new value Change the attribute value of an HTML element
element.style.property = new style Change the style of an HTML element
Method Description
element.setAttribute(attribute, value) Change the attribute value of an HTML element

Adding and Deleting Elements


Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(new, old) Replace an HTML element
document.write(text) Write into the HTML output stream

Adding Events Handlers


Method Description
document.getElementById(id).onclick = Adding event handler code to an onclick
function(){code} event

Finding HTML Objects


Property Description
document.anchors Returns all <a> elements that have a name attribute
document.body Returns the <body> element
document.doctype Returns the document's doctype
document.documentElement Returns the <html> element
document.domain Returns the domain name of the document server
document.forms Returns all <form> elements
document.head Returns the <head> element
document.images Returns all <img> elements
document.lastModified Returns the date and time the document was updated
document.links Returns all <a> elements that have a href attribute
document.scripts Returns all <script> elements
document.title Returns the <title> element
document.URL Returns the complete URL of the document

JavaScript is also used to change some specifics given below;

Changing the Value of an Attribute


To change the value of an HTML attribute, use this syntax:
document.getElementById(id).attribute = new value;

Changing HTML Style


To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property = new style

User Defined Objects;


Creating User-defined JavaScript Object Type
We can define a custom object type by writing a constructor function where the name of the function
should start with an uppercase alphabet for example Car, Cup, Human, etc.
The constructor function is defined just as we define any other user-defined
Syntax:
function Xyz(param1, param2, ... , paramN)
{
this.param1 = param1;
this.param2 = param2;
...
this.paramN = paramN;
}
In JavaScript we use this keyword to reference the current object, hence in the constructor function
we create new properties (param1, param2, ...) for the object type and we set the values for the
parameters provided at the time of object creation using the new keyword.

And object can be created by initializing the constructor as follows:


let customObj = new Xyz(paramValue1, paramValue2, paramValue3, ... , paramValueN);

Example:
<!doctype html>
<head>
<title>Create User-defined Object in JavaScript</title>
</head>
<body>
<script>
/* defining a new constructor function */
function Bike(company, model, year) {
this.company = company;
this.model = model;
this.year = year;
}

/* creating the object */


let myBike = new Bike("KTM", "Duke", 2010);

document.write(myBike.company+"<br/>"+myBike.model+"<br/>"+myBike.year);
</script>
</body>
</html>

4.8 Using a user-defined Object as Property of another Object


Let's define one more object type and then use it as a value in our Bike object type.

We have defined a new object type Person below, and have also added a new property owner in
the Bike object type in which we will store the Person objects.

Example:

<!doctype html>
<head>
<title>Object in Object Example JavaScript</title>
</head>
<body>
<script>
/* defining a new constructor function */
function Person(name, age, city) {
this.name = name;
this.age = age;
this.city = city;
}

function Bike(company, model, year, owner) {


this.company = company;
this.model = model;
this.year = year;
this.owner = owner;
}

/* creating the object */


let person = new Person("John Wick", 30, "New York");
let myBike = new Bike("KTM", "Duke", 2010, person);

document.write(myBike.company+"<br/>"+myBike.model+"<br/>"+myBike.year+"<br/>"
+myBike.owner.name);
</script>
</body>
Note: We can do anything with user-defined object types in JavaScript.

Using the Object.create method


If you do not want to get into the trouble of defining a constructor method to define a user-defined
object type, you can use the Object.create() method to create an object of any prototype object which
is already defined.
Let's take an example to understand this.
let Bike = {
company: 'KTM', // Default value of properties
model: 'Duke 390',
show: function() { // Method to display property type of Bike
document.write(this.company+" "+this.model);
}
};

// using Object.create to create a new object


let newBike = Object.create(Bike);
newBike.company = 'Yamaha';
newBike.model = 'R15';
newBike.show();

Output:
Yamaha R15

As you can see in the code above, we can use the Object.create method to create a new object using
an already defined object, and then if required we can change the properties values and use the
object function too.
So that's it for this tutorial. From the next tutorial, we will cover the various built-in JavaScript
objects one by one.

Event Handling and Form Validation

A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.
To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:
onclick=JavaScript

Examples of HTML events:


 When a user clicks the mouse
 When a web page has loaded
 When an image has been loaded
 When the mouse moves over an element
 When an input field is changed
 When an HTML form is submitted
 When a user strokes a key
In this example, the content of the <h1> element is changed when a user clicks on it:
<!DOCTYPE html>
<html>
<body>
<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>
</body>
</html>

Example: In this example, a function is called from the event handler:


<!DOCTYPE html>
<html> “this” is for <h1> tag
<body>
<h1 onclick="changeText(this)">Click on this text!</h1>

<script>
function changeText(tag) {
tag.innerHTML = "Changed Text!";
}
</script>
</body>
</html>

HTML Event Attributes

<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the date.</p>
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
</body>
</html>

Assign Events Using the HTML DOM


<!DOCTYPE html>
<html>
<body>
<p>Click "Try it" to execute the displayDate() function.</p>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
document.getElementById("myBtn").onclick = displayDate;

function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
</body>
</html>

The onload and onunload Events

The onload and onunload events are triggered when the user enters or leaves the page.
The onload event can be used to check the visitor's browser type and browser version, and load the
proper version of the web page based on the information.
The onload and onunload events can be used to deal with cookies.

<!DOCTYPE html>
<html>
<body onload="checkCookies()">
<p id="demo"></p>
<script>
function checkCookies() {
var text = "";
if (navigator.cookieEnabled == true) {
text = "Cookies are enabled.";
} else {
text = "Cookies are not enabled.";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>

The onchange Event


The onchange event is often used in combination with validation of input fields.
Below is an example of how to use the onchange. The upperCase() function will be called when a
user changes the content of an input field.
Example:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" onchange="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to
upper case.</p>
</body>
</html>

The onmouseover and onmouseout Events

The onmouseover and onmouseout events can be used to trigger a function when the user mouses
over, or out of, an HTML element:

Example:
<!DOCTYPE html>
<html>
<body>
<style>
div{
background-color:#D94A38;
width:120px;
height:20px;
padding:40px;
color:white;
}
</style>
<div onmouseover="mOver(this)" onmouseout="mOut(this)">
Mouse Over Me</div>

<script>
function mOver(obj) {
obj.innerHTML = "Thank You";
obj.style.background="green";
}

function mOut(obj) {
obj.innerHTML = "Mouse Over Me";
obj.style.background="#D94A38";
}
</script>
</body>
</html>

The onmousedown, onmouseup and onclick Events

The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First when a
mouse-button is clicked, the onmousedown event is triggered, then, when the mouse-button is
released, the onmouseup event is triggered, finally, when the mouse-click is completed, the onclick
event is triggered.

Example:
<!DOCTYPE html>
<html>
<style>
div{
background-color:#D94A38;
width:120px;
height:20px;
padding:40px;
color:white;
}
</style>

<body>
<div onmousedown="mDown(this)" onmouseup="mUp(this)">
Click Me</div>
<script>
function mDown(obj) {
obj.style.backgroundColor = "#1ec5e5";
obj.innerHTML = "Release Me";
}

function mUp(obj) {
obj.style.backgroundColor="#D94A38";
obj.innerHTML="Thank You";
}
</script>
</body>
</html>

DOM Event Listeners:

<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to execute a function when a user
clicks on a button.</p>
<button id="myBtn">Try it</button>
<script>
document.getElementById("myBtn").addEventListener("click", myFunction);

function myFunction() {
alert ("Hello World!");
}
</script>
</body>
</html>

You can add events of different types to the same element:


Example
element.addEventListener("mouseover", myFunction);
element.addEventListener("click", mySecondFunction);
element.addEventListener("mouseout", myThirdFunction);
JavaScript Forms
JavaScript Form Validation
HTML form validation can be done by JavaScript.
If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the form
from being submitted:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>

<form name="myForm" action="/action_page.php" onsubmit="return validateForm()"


method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>

Automatic HTML Form Validation without JavaScript

<!DOCTYPE html>
<html>
<body>

<form action="/action_page.php" method="post">


<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>

<p>If you click submit, without filling out the text field,
your browser will display an error message.</p>
</body>
</html>

Data Validation

Data validation is the process of ensuring that user input is clean, correct, and useful.

Typical validation tasks are:


 has the user filled in all required fields?
 has the user entered a valid date?
 has the user entered text in a numeric field?
Most often, the purpose of data validation is to ensure correct user input.
Validation can be defined by many different methods, and deployed in many different ways.
Server side validation is performed by a web server, after input has been sent to the server.
Client side validation is performed by a web browser, before input is sent to a web server.

Error Handling, Handling Cookies

Error Handling:
 The try statement lets you test a block of code for errors.
 The catch statement lets you handle the error.
 The throw statement lets you create custom errors.
 The finally statement lets you execute code, after try and catch, regardless of the result.

Errors are occurred frequently in any source code of JavaScript and can be occurred when user
provide wrong input and other unforeseeable errors.
Example:
<html>

<body>

<h2>JavaScript Error Handling</h2>

<p>Demonstrating how to use <b>catch</b> to display an error.</p>

<p id="demo"></p>

<script>

try {

alerto("Hello Guys!");
}

catch(err) {

document.getElementById("demo").innerHTML = err.message;

</script>

</body>

</html>
The throw Statement
The throw statement allows you to create a custom error.
Technically you can throw an exception (throw an error).

The exception can be a JavaScript String, a Number, a Boolean or an Object:


throw "Too big"; // throw a text
throw 500; // throw a number

If you use throw together with try and catch, you can control program flow and generate custom
error messages.
Example:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript try catch</h2>

<p>Any number between 5 and 10:</p>

<input id="demo" type="text">


OR
<input id="demo" type="number" min="5" max="10" step="1">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="pid"></p>

<script>
function myFunction() {
const message = document.getElementById("pid");
message.innerHTML = "";
let x = document.getElementById("demo").value;
try {
if(x == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x); //conversion from text to integer
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
}
</script>
</body>
</html>
Finally block:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result
}
Adding the finally block after catch block in the program above as below;
finally {
document.getElementById("demo").placeholder = "input between 5 and 10";
}

The Error Object


JavaScript has a built in error object that provides error information when an error occurs.
The error object provides two useful properties: name and message.

Error Object Properties


Property Description
name Sets or returns an error name
message Sets or returns an error message (a string)

Error Name Values


Six different values can be returned by the error name property:
Error Name Description
EvalError An error has occurred in the eval() function
RangeError A number "out of range" has occurred
ReferenceError An illegal reference has occurred
SyntaxError A syntax error has occurred
TypeError A type error has occurred
URIError An error in encodeURI() has occurred

Range Error
A RangeError is thrown if you use a number that is outside the range of legal values.
For example: You cannot set the number of significant digits of a number to 500.

Example
let num = 1;
try {
//toPrecision function is used to display decimal numbers to specific digits.
num.toPrecision(500); // A number cannot have 500 significant digits
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}

Reference Error
A ReferenceError is thrown if you use (reference) a variable that has not been declared:

Example
let x = 5;
try {
x = y + 1; // y cannot be used (referenced)
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}

Syntax Error
A SyntaxError is thrown if you try to evaluate code with a syntax error.

Example
try {
eval("alert('Hello)"); // Missing ' will produce an error
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
Note:
Newer version of JavaScript uses SyntaxError for EvalError.

Type Error
A TypeError is thrown if you use a value that is outside the range of expected types:
Example
let num = 1;
try {
num.toUpperCase(); // You cannot convert a number to upper case
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}

URI (Uniform Resource Identifier) Error


A URIError is thrown if you use illegal characters in a URI function:

Example
try {
decodeURI("%%%"); // You cannot URI decode percent signs
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;

4.10 Cookie Handling:


Cookies:
Cookies are text files with small pieces of data — like a username and password — that are used to
identify your computer as you use a computer network. Specific cookies known as HTTP cookies
are used to identify specific users and improve your web browsing experience.

Data stored in a cookie is created by the server upon your connection. This data is labeled with an ID
unique to you and your computer.

When the cookie is exchanged between your computer and the network server, the server reads the
ID and knows what information to specifically serve to you.

Example:
Cookies.js
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=http://127.0.0.1/"; //live serv
alert("Cookie with " + cvalue + " is set");
}

function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}

function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
alert("No cookies are set");
}
}
function cookieSet() {
var user = getCookie("username");
if (user == "") {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 30); //this takes parameters name, value, days
}
}
}

function deleteCookie() {
var user = getCookie("username");
if (user == "") {
alert("No cookies to delete");
} else {
alert(user + " cookie is deleted");
}
document.cookie = "username ='" + user + "'; expires=Thu, 01 Jan 1970 00:00:00 UTC; domain
=127.0.0.1";
}

Cookies.html
<!DOCTYPE html>
<html>

<head>
<script src="Cookies.js"></script>
</head>
<style>
button {
width: 200px;
height: 50px;
font-size: large;
color: whitesmoke;
}

#check {
background-color: green;
}

#delete {
background-color: red;
}

#set {
background-color: blue;
}
</style>

<body>
<h2>Operations on Cookie</h2>

<h3>Check the cookies available for particular domain/path</h3>


<hr size=3 color="green">
<button id="check" onclick="checkCookie()">Check Cookie
</button>
<h3>Set the cookie if there are'nt any</h3>
<hr size=3 color="blue">
<button id="set" onclick="cookieSet()">Set Cookie</button>
<h3>Delete the cookies from the domain/path</h3>
<hr size=3 color="red">
<button id="delete" onclick="deleteCookie()">Delete cookie
</button>

</body>

</html>

4.11 jQuery Syntax; jQuery Selectors, Events and Effects


What is jQuery?
jQuery is a lightweight, "write less, do more", JavaScript library.
The purpose of jQuery is to make it much easier to use JavaScript on your website.
jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and
wraps them into methods that you can call with a single line of code.
jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM
manipulation.
The jQuery library contains the following features:
 HTML/DOM manipulation
 CSS manipulation
 HTML event methods
 Effects and animations
 AJAX
 Utilities
Tip: In addition, jQuery has plugins for almost any task out there.

Why JQuery?
There are lots of other JavaScript libraries out there, but jQuery is probably the most popular, and
also the most extendable.
Many of the biggest companies on the Web use jQuery, such as:
 Google
 Microsoft
 IBM
 Netflix
Note: To get JQuery need to download a latest file from jquery.com.

Basic syntax is: $(selector).action()


 A $ sign to define/access jQuery
 A (selector) to "query (or find)" HTML elements
 A jQuery action() to be performed on the element(s)
Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test".
$("#test").hide() - hides the element with id="test".
Note: For the effective use of JQuery we need to use <script> tag and jquery file path inside the
script tag.
Let‘s go through an example demonstration;

<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
$("p").click(function() {
$(this).hide();
});
});
</script>
</head>
<body>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>
</body>
</html>

Output will be the content will hide whenever the p tags are clicked.

jQuery Selectors
jQuery selectors allow you to select and manipulate HTML element(s).
jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes,
types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in
addition, it has some own custom selectors.
All selectors in jQuery start with the dollar sign and parentheses: $().

The element Selector


The jQuery element selector selects elements based on the element name.
You can select all <p> elements on a page like this:
$("p")
Example
When a user clicks on a button, all <p> elements will be hidden:
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});

The #id Selector


The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.
An id should be unique within a page, so you should use the #id selector when you want to find a
single, unique element.
To find an element with a specific id, write a hash character, followed by the id of the HTML
element:
$("#test")

Example
When a user clicks on a button, the element with id="test" will be hidden:
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});

The .class Selector


The jQuery .class selector finds elements with a specific class.
To find elements with a specific class, write a period character, followed by the name of the class:
$(".test")
Example
When a user clicks on a button, the elements with class="test" will be hidden:
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});

More selectors used in JQuery as follows:

Syntax Description
$("*") Selects all elements
$(this) Selects the current HTML element
$("p.intro") Selects all <p> elements with class="intro"
$("p:first") Selects the first <p> element
$("ul li:first") Selects the first <li> element of the first <ul>
$("ul li:first-child") Selects the first <li> element of every <ul>
$("[href]") Selects all elements with an href attribute
$("a[target='_blank']") Selects all <a> elements with a target attribute value equal to "_blank"
$("a[target!='_blank']") Selects all <a> elements with a target attribute value NOT equal to
"_blank"
$(":button") Selects all <button> elements and <input> elements of type="button"
$("tr:even") Selects all even <tr> elements
$("tr:odd") Selects all odd <tr> elements

What are Events?


All the different visitors' actions that a web page can respond to are called events.
An event represents the precise moment when something happens.
Examples:
 moving a mouse over an element
 selecting a radio button
 clicking on an element
The term "fires/fired" is often used with events. Example: "The keypress event is fired, the moment
you press a key".
Here are some common DOM events:
Mouse Events Keyboard Events Form Events Document/Window Events
click keypress submit load
dblclick keydown change resize
mouseenter keyup focus scroll
mouseleave blur unload

jQuery Syntax For Event Methods


In jQuery, most DOM events have an equivalent jQuery method.
To assign a click event to all paragraphs on a page, you can do this:
$("p").click();
The next step is to define what should happen when the event fires. You must pass a function to the
event:
$("p").click(function(){
// action goes here!!
});

Commonly Used jQuery Event Methods


$(document).ready()
The $(document).ready() method allows us to execute a function when the document is fully loaded.
This event is already explained in the jQuery Syntax chapter.

click()
The click() method attaches an event handler function to an HTML element.
The function is executed when the user clicks on the HTML element.
The following example says: When a click event fires on a <p> element; hide the
current <p> element:
$("p").click(function(){
$(this).hide();
});

dblclick()
The dblclick() method attaches an event handler function to an HTML element.
The function is executed when the user double-clicks on the HTML element:
$("p").dblclick(function(){
$(this).hide();
});

mouseenter()
The mouseenter() method attaches an event handler function to an HTML element.
The function is executed when the mouse pointer enters the HTML element:
$("#p1").mouseenter(function(){
alert("You entered p1!");
});
mouseleave()
The mouseleave() method attaches an event handler function to an HTML element.
The function is executed when the mouse pointer leaves the HTML element:
$("#p1").mouseleave(function(){
alert("Bye! You now leave p1!");
});

mousedown()
The mousedown() method attaches an event handler function to an HTML element.
The function is executed, when the left, middle or right mouse button is pressed down, while the
mouse is over the HTML element:
$("#p1").mousedown(function(){
alert("Mouse down over p1!");
});

mouseup()
The mouseup() method attaches an event handler function to an HTML element.
The function is executed, when the left, middle or right mouse button is released, while the mouse is
over the HTML element:
$("#p1").mouseup(function(){
alert("Mouse up over p1!");
});

hover()
The hover() method takes two functions and is a combination of
the mouseenter() and mouseleave() methods.
The first function is executed when the mouse enters the HTML element, and the second function is
executed when the mouse leaves the HTML element:
$("#p1").hover(function(){
alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
});

focus()
The focus() method attaches an event handler function to an HTML form field.
The function is executed when the form field gets focus:
$("input").focus(function(){
$(this).css("background-color", "#cccccc");
});

blur()
The blur() method attaches an event handler function to an HTML form field.
The function is executed when the form field loses focus:
$("input").blur(function(){
$(this).css("background-color", "#ffffff");
});
The on() Method
The on() method attaches one or more event handlers for the selected elements.
Attach a click event to a <p> element:
$("p").on("click", function(){
$(this).hide();
});
Attach multiple event handlers to a <p> element:
$("p").on({
mouseenter: function(){
$(this).css("background-color", "lightgray");
},
mouseleave: function(){
$(this).css("background-color", "lightblue");
},
click: function(){
$(this).css("background-color", "yellow");
}
});

jQuery Effects [hide() and show()]


With jQuery, you can hide and show HTML elements with the hide() and show() methods:
$("#hide").click(function(){
$("p").hide();
});

$("#show").click(function(){
$("p").show();
});
Syntax:
$(selector).hide(speed,callback);

$(selector).show(speed,callback);
The optional speed parameter specifies the speed of the hiding/showing, and can take the following
values: "slow", "fast", or milliseconds.
The optional callback parameter is a function to be executed after the hide() or show() method
completes (you will learn more about callback functions in a later chapter).
The following example demonstrates the speed parameter with hide():
$("button").click(function(){
$("p").hide(1000);
});
jQuery toggle()
You can also toggle between hiding and showing an element with the toggle() method.
Shown elements are hidden and hidden elements are shown:
$("button").click(function(){
$("p").toggle();
});
Syntax:
$(selector).toggle(speed,callback);
The optional speed parameter can take the following values: "slow", "fast", or milliseconds.
The optional callback parameter is a function to be executed after toggle() completes.
JQuery Fade:
fadeIn function fadeToggle function

$("button").click(function(){ $("button").click(function(){
$("#div1").fadeIn(); $("#div1").fadeToggle();
$("#div2").fadeIn("slow"); $("#div2").fadeToggle("slow");
$("#div3").fadeIn(3000); $("#div3").fadeToggle(3000);
}); });
fadeout function fadeTo function

$("button").click(function(){ $("button").click(function(){
$("#div1").fadeOut(); $("#div1").fadeTo("slow", 0.15);
$("#div2").fadeOut("slow"); $("#div2").fadeTo("slow", 0.4);
$("#div3").fadeOut(3000); $("#div3").fadeTo("slow", 0.7);
}); });

JQuery Slide:
slideDown function slideUp function
$("#flip").click(function(){ $("#flip").click(function(){
$("#panel").slideDown(); $("#panel").slideUp();
}); });

slideToggle function
$("#flip").click(function(){
$("#panel").slideToggle();
});

JQuery Animate:
$("button").click(function(){ $("button").click(function(){
$("div").animate({left: '250px'}); $("div").animate({
}); left: '250px',
opacity: '0.5',
height: '150px',
width: '150px'
});
});
$("button").click(function(){ $("button").click(function(){
$("div").animate({ $("div").animate({
left: '250px', height: 'toggle'
height: '+=150px', });
width: '+=150px' });
});
});
$("button").click(function(){ $("button").click(function(){
var div = $("div"); var div = $("div");
div.animate({height: '300px', div.animate({left: '100px'}, "slow");
opacity: '0.4'}, "slow"); div.animate({fontSize: '3em'}, "slow");
div.animate({width: '300px', });
opacity: '0.8'}, "slow");
div.animate({height: '100px',
opacity: '0.4'}, "slow");
div.animate({width: '100px',
opacity: '0.8'}, "slow");
});

Stop JQuery:
It stops the JQuery if we click the stop before 5000 milliseconds.
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown(5000);
});
$("#stop").click(function(){
$("#panel").stop();
});
});

Chaining JQuery:
$(document).ready(function(){
$("button").click(function(){
$("#p1").css("color", "red")
.slideUp(2000)
.slideDown(2000);
});
});

JQuery UI: [not in course]


JqueryUI is a powerful Javascript library built on top of jQuery JavaScript library. UI stands for
User interface, It is a set of plug-ins for jQuery that adds new functionalities to the jQuery core
library.
The set of plug-ins in JqueryUI includes interface interactions, effects, animations, widgets, and
themes built on top of jQuery JavaScript Library.

Some of the JQuery UI are listed below:


Interactions
Interactions add basic mouse-based behaviors to any element. You can create sortable lists, resizable
elements, drag & drop behaviors and more with just a few lines of code. Interactions also make great
building blocks for more complex widgets and applications.
 Draggable
 Droppable
 Resizable
 Selectable
 Sortable
Example:
Draggable
<html>

<head>
<style>
#draggable {
width: 150px;
height: 150px;
padding: 0.5em;
}
</style>
<script src="jquery.js"></script>
<script src="jquery-ui.js"></script>
<script>
$(function() {
$("#draggable").draggable();
});
</script>
</head>
<body>
<div id="draggable" class="ui-widget-content">
<p>Drag me around</p>
</div>
</body>
</html>

Widgets
Widgets are full-featured UI controls that bring the richness of desktop applications to the Web. All
widgets provide a solid core with plenty of extension points for customizing behavior, as well as full
theming support.
Accordion
<html>
<head>
<script src="jquery.js"></script>
<script src="jquery-ui.js"></script>
<script>
$(function() {
$("#accordion").accordion();
});
</script>
</head>

<body>
<div id="accordion">
<h3>Section 1</h3>
<div>
<p>
This is section one.
</p>
</div>
<h3>Section 2</h3>
<div>
<p>
This is section two </p>
</div>
<h3>Section 3</h3>
<div>
<p>
This is section three.
</p>
</div>
</div>
</body>
</html>

Autocomplete
<html>
<head>
<script src="jquery.js"></script>
<script src="jquery-ui.js"></script>
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
];
$("#tags").autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
Datepicker
<!doctype html>
<html lang="en">

<head>
<script src="jquery.js"></script>
<script src="jquery-ui.js"></script>
<script>
$(function() {
$("#datepicker").datepicker();
});
</script>
</head>
<body>
<p>Date: <input type="text" id="datepicker"></p>
</body>
</html>
Some more JQuery UIs are shown below;
 Button
 Checkboxradio
 Controlgroup
 Dialog
 Menu
 Progressbar
 Selectmenu
 Slider
 Spinner
 Tabs
 Tooltip

4.12 Introduction to JSON

What is JSON?
JSON stands for JavaScript Object Notation

 JSON is a lightweight data-interchange format


 JSON is plain text written in JavaScript object notation
 JSON is used to send data between computers
 JSON is language independent

Why Use JSON?


The JSON format is syntactically similar to the code for creating JavaScript objects. Because of this,
a JavaScript program can easily convert JSON data into JavaScript objects.
Since the format is text only, JSON data can easily be sent between computers, and used by any
programming language.
JavaScript has a built in function for converting JSON strings into JavaScript objects:
JSON.parse()
JavaScript also has a built in function for converting an object into a JSON string:
JSON.stringify()

Storing Data
When storing data, the data has to be a certain format, and regardless of where you choose to store
it, text is always one of the legal formats.
JSON makes it possible to store JavaScript objects as text.

JSON Syntax Rules


JSON syntax is derived from JavaScript object notation syntax:
 Data is in name/value pairs
 Data is separated by commas
 Curly braces hold objects
 Square brackets hold arrays

JSON Data - A Name and a Value


JSON data is written as name/value pairs (aka key/value pairs).
A name/value pair consists of a field name (in double quotes), followed by a colon, and followed by
a value:
Example
"name":"John"

JSON Values
In JSON, values must be one of the following data types:
 a string
 a number
 an object
 an array
 a boolean
 null

XML vs JASON
Both JSON and XML can be used to receive data from a web server.

The following JSON and XML examples both define students object, with an array of 3 students:
JSON Example
{"employees":[
{ "firstName":"Harendra", "lastName":"Bista" },
{ "firstName":"Deshant", "lastName":"Devkota" },
{ "firstName":"Sagar", "lastName":"Shrestha" }
]}

XML Example
<employees>
<employee>
<firstName>Harendra</firstName> <lastName>Bista</lastName>
</employee>
<employee>
<firstName>Deshant</firstName> <lastName>Devkota</lastName>
</employee>
<employee>
<firstName>Sagar</firstName> <lastName>Shrestha</lastName>
</employee>
</employees>
JSON is Like XML Because
 Both JSON and XML are "self describing" (human readable)
 Both JSON and XML are hierarchical (values within values)
 Both JSON and XML can be parsed and used by lots of programming languages
 Both JSON and XML can be fetched with an XMLHttpRequest

JSON is Unlike XML Because


 JSON doesn't use end tag
 JSON is shorter
 JSON is quicker to read and write
 JSON can use arrays
The biggest difference is:
XML has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript function.

Why JSON is Better Than XML?


XML is much more difficult to parse than JSON.
JSON is parsed into a ready-to-use JavaScript object.
For AJAX applications, JSON is faster and easier than XML:
Using XML
 Fetch an XML document
 Use the XML DOM to loop through the document
 Extract values and store in variables
Using JSON
 Fetch a JSON string
 JSON.Parse the JSON string

Data Types in JASON

JSON Strings
Strings in JSON must be written in double quotes.
Example
{"name":"John"}

JSON Numbers
Numbers in JSON must be an integer or a floating point.
Example
{"age":30}

JSON Objects
Values in JSON can be objects.
Example
{
"employee":{"name":"John", "age":30, "city":"New York"}
}
Note: Objects as values in JSON must follow the JSON syntax.

JSON Arrays
Values in JSON can be arrays.
Example
{
"employees":["John", "Anna", "Peter"]
}

JSON Booleans
Values in JSON can be true/false.
Example
{"sale":true}

JSON null
Values in JSON can be null.
Example
{"middlename":null}

JASON.parse():
JASON.parse() function is used to convert the JASON text into JS objects/arrays.
1. Text as JASON
<html>
<body>
<h2>Creating an JS Object from a JSON String</h2>
<p id="demo"></p>
<script>
const txt = '{"name":"John", "age":30, "city":"New York"}'
const obj = JSON.parse(txt);//converting JASON to JavaScript object
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
</script>
</body>
</html>

2. Array as JASON
When using the JASON.parse() on JASON derived from an array, the method will return a JS array
instead of JS object.
Example:
const text = '["Ford", "BMW", "Audi", "Fiat"]';
const myArr = JSON.parse(text);

3. JASON.stringify():
JASON.stringify() function is used to change the JASON text/array into a string value.
<h2>Create a JSON string from a JavaScript object.</h2>
<p id="demo"></p>
<script>
const obj = {name: "John", age: 30, city: "New York"};
OR
const obj = ["John", "Peter", "Sally", "Jane"];
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>
Unit 5: AJAX and XML (7 Hrs.) Basics of AJAX; Introduction to XML and its
Application; Syntax Rules for creating XML document; XML Elements; XML
Attributes; XML Tree; XML Namespace; XML schema languages: Document Type
Definition(DTD), XML Schema Definition (XSD); XSD Simple Types, XSD
Attributes; XSD Complex Types; XML Style Sheets (XSLT), Xquery
5.1 AJAX:
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better,
faster, and more interactive web applications with the help of XML, HTML, CSS, and Java Script.
AJAX is used to;
 Update a web page without reloading the page
 Request data from a server - after the page has loaded
 Receive data from a server - after the page has loaded
 Send data to a server - in the background

AJAX is based on the followings −

 Browser-based presentation using HTML and Cascading Style Sheets (CSS).


 Data is stored in XML format and fetched from the server.
 Behind-the-scenes data fetches using XMLHttpRequest objects in the browser.
 JavaScript to make everything happen.
AJAX cannot work independently. It is used in combination with other technologies to create
interactive webpages.

JavaScript

 Loosely typed scripting language.


 JavaScript function is called when an event occurs in a page.
 Used for the whole AJAX operation.

DOM

 API for accessing and manipulating structured documents.


 Represents the structure of XML and HTML documents.

CSS

1. Allows for a clear separation of the presentation style from the content and may be changed
programmatically by JavaScript

XMLHttpRequest

 JavaScript object that performs asynchronous interaction with the server.

Examples:
Google maps, yahoo maps, Google suggest, Gmail, etc. are some good examples that are using
AJAX for quick execution of their applications.

The backbone of AJAX is the XMLHttpRequest object.

The XMLHttpRequest Object

All modern browsers support the XMLHttpRequest object. The XMLHttpRequest object is used to
exchange data with a server behind the scenes. This means that it is possible to update parts of a web
page, without reloading the whole page.

Create an XMLHttpRequest Object


All modern browsers (Chrome, IE7+, Firefox, Safari, and Opera) have a built-in XMLHttpRequest
object.
Syntax;
variable = new XMLHttpRequest();

Old versions of Internet Explorer (IE5 and IE6) use an ActiveX Object:
variable = new ActiveXObject("Microsoft.XMLHTTP");

To handle all browsers, including IE5 and IE6, check if the browser supports the XMLHttpRequest
object. If it does, create an XMLHttpRequest object, if not, create an ActiveXObject:
Example
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

Ajax Request:
The XMLHttpRequest object is used to exchange data with a server.
To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:

xhttp.open("GET", "harendra.txt", true);


xhttp.send();

Method Description
open(method, url, async) Specifies the type of request
method: the type of request: GET or POST
url: the server (file) location
async: true (asynchronous) or false (synchronous)
send() Sends the request to the server (used for GET)
send(string) Sends the request to the server (used for POST)
Note: Async=true

When using async=true, specify a function to execute when the response is ready in the
onreadystatechange event.

Ajax Response:
Server Response Properties
Property Description
responseText get the response data as a string
responseXML get the response data as XML data

The onreadystatechange Property

The readyState property holds the status of the XMLHttpRequest.


The onreadystatechange property defines a function to be executed when the readyState changes.
The status property and the statusText property holds the status of the XMLHttpRequest object.

Property Description
onreadystatechange Defines a function to be called when the readyState property changes
readyState Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status 200: "OK"
403: "Forbidden"
404: "Page not found"
statusText Returns the status-text (e.g. "OK" or "Not Found")

Note: When readyState is 4 and status is 200, the response is ready.

Complete Example:
<html>

<body>
<div id="ajaxid">
<h2>Change This content only without reloading the page.</h2>
</div>
<button type="button" onclick="loadDoc('harendra.txt')">Change Content</button>

<script>
function loadDoc(url) { //takes file as a parameter
var xhttpR = new XMLHttpRequest(); //request object of XMLHttpRequest()
xhttpR.onreadystatechange = function() { //this is for asynchronous
if (xhttpR.readyState == 4 && xhttpR.status == 200) { //4 means request is finished and
response is ready and 200 meand OK
document.getElementById("ajaxid").innerHTML = xhttpR.responseText; //take text as a
response
}
};
xhttp.open("GET", url, true); //Get method, url path of a file, true for asynchronous
xhttp.send(); //send the file text as response
}
</script>
</body>

</html>

5.2 Introduction to XML and its Application:


In short:
 XML stands for EXtensible Markup Language
 XML is a markup language much like HTML.
 XML was designed to describe data, not to display data as HTML
 XML tags are not predefined. You must define your own tags.
 XML is designed to be self-descriptive.
 XML is a W3C Recommendation since February 10, 1998.

The essence of XML is in its name: Extensible Markup Language.

Extensible
XML is extensible. It lets you define your own tags, the order in which they occur, and how they
should be processed or displayed. Another way to think about extensibility is to consider that XML
allows all of us to extend our notion of what a document is: it can be a file that lives on a file server,
or it can be a transient piece of data that flows between two computer systems (as in the case of Web
Services).
Markup
The most recognizable feature of XML is its tags, or elements (to be more accurate). In fact, the
elements you‘ll create in XML will be very similar to the elements you‘ve already been creating in
your HTML documents. However, XML allows you to define your own set of tags.
Language
XML is a language that‘s very similar to HTML. It‘s much more flexible than HTML because it
allows you to create your own custom tags. However, it‘s important to realize that XML is not just a
language. XML is a meta-language: a language that allows us to create or define other languages.
For example, with XML we can create other languages, such as RSS, MathML (a mathematical
markup language), and even tools like XSLT.

Moral: XML is a software- and hardware-independent tool for carrying information especially in
WEB.
<?xml version="9.0" encoding="UTF-8"?>
<note>
<to>Harendra</to>
<from>Deshant</from>
<heading>Reminder</heading>
<body>Don't forget to give assignment this weekend!</body>
</note>

The first line is the XML declaration. It defines the XML version (1.0). The next line describes the
root element of the document (like saying: "this document is a note"). The next 4 lines describe 4
child elements of the root (to, from, heading, and body) and finally the last line defines the end of the
root element.

Q. What are the advantages of XML over the HTML?

XML is not replacement for HTML rather both were designed with different goals:
 XML was designed to describe data, with focus on what data is
 HTML was designed to display data, with focus on how data looks HTML is about displaying
information, while XML is about carrying information. Actually, XML does not DO anything. XML
was created to structure, store, and transport information.
The following example is a note to Harendra, from Deshant, stored as XML:
<note>
<to>Harendra</to>
<from>Deshant</from>
<heading>Reminder</heading>
<body>Don't forget to give assignment this weekend!</body>
</note>

The note above is quite self descriptive. It has sender and receiver information, it also has a heading
and a message body. But still, this XML document does not DO anything. It is just information
wrapped in tags. Someone must write a piece of software to send, receive or display it. The tags in
the example above (like and ) are not defined in any XML standard. These tags are "invented" by the
author of the XML document. That is because the XML language has no predefined tags. The tags
used in HTML are predefined. HTML documents can only use tags defined in the HTML standard
(like, <p>, <h1>, <hr>, <br>, etc.). XML allows the author to define his/her own tags and his/her
own document structure.

How Can XML be used? [Benefits]


XML is used in many aspects of web development, often to simplify data storage and sharing.
1. XML Separates Data from HTML: If you need to display dynamic data in your HTML
document, it will take a lot of work to edit the HTML each time the data changes. With XML, data
can be stored in separate XML files. This way you can concentrate on using HTML/CSS for display
and layout, and be sure that changes in the underlying data will not require any changes to the
HTML. With a few lines of JavaScript code, you can read an external XML file and update the data
content of your web page.
2. XML Simplifies Data Sharing: In the real world, computer systems and databases contain data
in incompatible formats. XML data is stored in plain text format. This provides a software- and
hardwareindependent way of storing data. This makes it much easier to create data that can be
shared by different applications.
3. XML Simplifies Data Transport: One of the most time-consuming challenges for developers is
to exchange data between incompatible systems over the Internet. Exchanging data as XML greatly
reduces this complexity, since the data can be read by different incompatible applications.
4. XML Simplifies Platform Changes: Upgrading to new systems (hardware or software
platforms), is always time consuming. Large amounts of data must be converted and incompatible
data is often lost. XML data is stored in text format. This makes it easier to expand or upgrade to
new operating systems, new applications, or new browsers, without losing data.
5. XML Makes Your Data More Available on diverse applications: Different applications can
access your data, not only in HTML pages, but also from XML data sources. With XML, your data
can be available to all kinds of "reading machines" (Handheld computers, voice machines, news
feeds, etc).
6. Internet Languages Written in XML: Several Internet languages are written in XML.
Here are some examples:
 XHTML
 WSDL for describing web services
 RSS languages for news feeds
 WAP and WML as markup languages for handheld devices.

5.3 Syntax Rules for creating XML document;


The syntax rules of XML are very simple and logical. The rules are easy to learn, and easy to use.
All XML Elements Must Have a Closing Tag: In HTML, some elements do not have to have a
closing tag:
<p>This is a paragraph.
<br>
In XML, it is illegal to omit the closing tag. All elements must have a closing tag:
<p>This is a paragraph.</p>
XML Tags are Case Sensitive:
XML tags are case sensitive. The<Letter> tag is different from the <letter>tag .
XML Elements Must be properly Nested: In HTML, you might see improperly nested elements:
<b><i>This text is bold and italic </b></i> .In XML, all elements must be properly nested within
each other: <b><i>This text is bold and italic </i></b>
XML Documents Must Have a Root Element: XML documents must contain one element that is
the parent of all other elements. This element is called the root element.
<root>
<child>
<subchild>.....</subchild>
</child>
</root>

XML Attribute Values Must be Quoted: XML elements can have attributes in name/value pairs
just like in HTML. In XML, the attribute values must always be quoted. Study the two XML
documents below. The first one is incorrect, the second is correct:
<note date=12/11/2007>
<to>Tove</to>
<from>Jani</from>
</note>
<note date="12/11/2007">
<to>Tove</to>
<from>Jani</from>
</note>
The error in the first document is that the date attribute in the note element is not quoted.

Entity References: Some characters have a special meaning in XML. If you place a character like
"<" inside an XML element, it will generate an error because the parser interprets it as the start of a
new element. This will generate an XML error:
E.g.
<message>if salary < 1000 then</message>
To avoid this error, replace the "<" character with an entity reference:
<message>if salary &lt; 1000 then</message>

There are 5 predefined entity references in XML:


 &lt; < less than
 &gt; > greater than
 &amp; & ampersand
 &apos; ' Apostrophe
 &quot; " quotation marks

Note: Only the characters "<" and "&" are strictly illegal in XML. The greater than character is
legal, but it is a good habit to replace it.

Comments in XML: The syntax for writing comments in XML is similar to that of HTML.
<!-- This is a comment -->

White-space is Preserved in XML: HTML truncates multiple white-space characters to one single
white-space:
HTML: Hello Tove
Output: Hello Tove
With XML, the white-space in a document is not truncated.

Q. Explain the XML syntax and structure rules.

XML Tree [XML Documents Form a Tree Structure] – XML Structure


XML documents form a tree structure that starts at "the root" and branches to "the leaves". XML
documents must contain a root element. This element is "the parent" of all other elements. The
elements in an XML document form a document tree. The tree starts at the root and branches to the
lowest level of the tree. All elements can have sub elements (child elements):

<root>
<child>
<subchild>.....</subchild>
</child>
</root>

The terms parent, child, and sibling are used to describe the relationships between elements. Parent
elements have children. Children on the same level are called siblings (brothers or sisters). All
elements can have text content and attributes (just like in HTML).

The XML of above tree is as follows:


<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
Q. What are the components of an XML file? Explain.
Q. Write the structure of an XML file with example.

5.4 XML Elements;


An XML document contains XML Elements. An XML element is everything from (including) the
element's start tag to (including) the element's end tag.
An element can contain:
 other elements
 text
 attributes
 or a mix of all of the above...
E.g.
<bookstore>
<book category="CHILDREN">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
In the example above, <bookstore> and <book> have element contents, because they contain other
elements. <book> also has an attribute (category="CHILDREN"). <title>, <author>, <year>, and
<price> have text content because they contain text.
Empty XML Elements
An alternative syntax can be used for XML elements with no content: Instead of writing a book
element (with no content) like this:
<book></book>
It can be written like this:
<book />
This sort of element syntax is called self-closing.

XML Naming Rules


XML elements must follow these naming rules:
 Names can contain letters, numbers, and other characters
 Names cannot start with a number or punctuation character
 Names cannot start with the letters xml (or XML, or Xml, etc)
 Names cannot contain spaces
 Any name can be used, no words are reserved
XML Attributes;
XML elements can have attributes, just like HTML. Attributes provide additional information about
an element. In HTML, attributes provide additional information about elements:
<img src="computer.gif">
<a href="demo.asp">
Attributes often provide information that is not a part of the data. In the example below, the file type
is irrelevant to the data, but can be important to the software that wants to manipulate the element:
<file type="gif">computer.gif</file>

XML Elements vs. Attributes


Take a look at these examples:
<person sex="female">
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
<person>
<sex>female</sex>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
In the first example sex is an attribute. In the last, sex is an element. Both examples provide the same
information. There are no rules about when to use attributes or when to use elements. Attributes are
handy in HTML. In XML, advice is to avoid them. Use elements instead, this makes parsing xml
uniform.

Proper way
The following three XML documents contain exactly the same information:
A date attribute is used in the first example:
<note date="10/01/2008">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
A date element is used in the second example:
<note>
<date>10/01/2008</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
An expanded date element is used in the third: (THE BEST PROPER WAY):

<note>
<date>
<day>10</day>
<month>01</month>
<year>2008</year>
</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Avoid XML Attributes?


Some of the problems with using attributes are:
 attributes cannot contain multiple values (elements can)
 attributes cannot contain tree structures (elements can)
 attributes are not easily expandable (for future changes)
Attributes are difficult to read and maintain. Use elements for data. Use attributes for information
that is not relevant to the data.

Don't end up like this:


<note day="10" month="01" year="2008" to="Tove" from="Jani" heading="Reminder"
body="Don't forget me this weekend!"> </note>

XML Attributes for Metadata


Sometimes ID references are assigned to elements. These IDs can be used to identify XML elements
in much the same way as the id attribute in HTML. This example demonstrates this:
<messages>
<note id="501">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note id="502">
<to>Jani</to>
<from>Tove</from>
<heading>Re: Reminder</heading>
<body>I will not</body>
</note>
</messages>
The id attributes above are for identifying the different notes. It is not a part of the note itself.
This means that metadata (data about data) should be stored as attributes, and the data itself should
be stored as elements.

5.5 XML Namespace;


XML Namespaces provide a method to avoid element name conflicts.
Name Conflicts
In XML, element names are defined by the developer. This often results in a conflict when trying to
mix
XML documents from different XML applications.
This XML carries HTML table information:
<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
This XML carries information about a table (a piece of furniture):
<table>
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>

If these XML fragments were added together, there would be a name conflict. Both contain a
<table> element, but the elements have different content and meaning. A user or an XML
application will not know how to handle these differences.

Solving the Name Conflict Using a Prefix


Name conflicts in XML can easily be avoided using a name prefix. This XML carries
information about an HTML table, and a piece of furniture:
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
In the example above, there will be no conflict because the two <table> elements have different
names.
XML Namespaces - The xmlns Attribute
When using prefixes in XML, a so-called namespace for the prefix must be defined. The namespace
is
defined by the xmlns attribute in the start tag of an element. The namespace declaration has the
following syntax:
xmlns:prefix="URI".
<root>
<h:table xmlns:h="http://www.w3.org/TR/html4/">
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table xmlns:f="http://www.w3schools.com/furniture">
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
In the example above, the xmlns attribute in the <table> tag give the h: and f: prefixes a qualified
namespace.
When a namespace is defined for an element, all child elements with the same prefix are associated
with the same namespace.
Namespaces can be declared in the elements where they are used or in the XML root element:
<root xmlns:h="http://www.w3.org/TR/html4/"
xmlns:f="http://www.w3schools.com/furniture">
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>

Uniform Resource Identifier (URI): A Uniform Resource Identifier (URI) is a string of characters
which identifies an Internet Resource. The most common URI is the Uniform Resource Locator
(URL) which identifies an Internet domain address.

Default Namespaces
Defining a default namespace for an element saves us from using prefixes in all the child elements. It
has the following syntax:
xmlns="namespaceURI"
This XML carries HTML table information:
<table xmlns="http://www.w3.org/TR/html4/">
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>

This XML carries information about a piece of furniture:


<table xmlns="http://www.w3schools.com/furniture">
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>

XML Encoding
XML documents can contain international characters, like Norwegian or French etc. To avoid errors,
you should specify the encoding used, or save your XML files as UTF-8.
Character Encoding
Character encoding defines a unique binary code for each different character used in a document. In
Computer terms, character encoding are also called character set, character map, code set, and code
page.
Unicode
Unicode is an industry standard for character encoding of text documents. It defines (nearly) every
possible international character by a name and a number.
Unicode has two variants: UTF-8 and UTF-16.
UTF = Universal character set Transformation Format.
UTF-8 uses 1 byte (8-bits) to represent characters in the ASCII set, and two or three bytes for
the rest.
UTF-16 uses 2 bytes (16 bits) for most characters, and four bytes for the rest.
UTF-8 - The Web Standard UTF-8 is the standard character encoding on the web. UTF-8 is
the default character encoding for HTML5, CSS, JavaScript, PHP, SQL, and XML.
XML Encoding
The first line in an XML document is called the prolog:
<?xml version="1.0"?>
The prolog is optional. Normally it contains the XML version number. It can also contain
information about the encoding used in the document. This prolog specifies UTF-8 encoding:
<?xml version="1.0" encoding="UTF-8"?>
The XML standard states that all XML software must understand both UTF-8 and UTF-16. UTF-8 is
the default for documents without encoding information. In addition, most XML software systems
understand encodings like ISO-8859-1, Windows-1252, and ASCII.
XML Errors
Most often, XML documents are created on one computer, uploaded to a server on a second
computer, and displayed by a browser on a third computer. If the encoding is not correctly
interpreted by all the three computers, the browser might display meaningless text, or you might get
an error message.

5.6 XML schema languages: Document Type Definition (DTD), XML Schema
Definition (XSD);
Board Question
Why is it important to specify a DTD for an XML document? Explain.
Well Formed and Valid XML Documents
A "Well Formed" XML document has correct XML syntax. A "Valid" XML document is a "Well
Formed" XML document, which also conforms to the rules of a Document Type Definition (DTD).
XML DTD.
The purpose of a DTD is to define the structure of an XML document. It defines the structure with a
list of legal elements and attributes.
Why Use a DTD?

data.
an use a standard DTD to verify that the data you receive from the outside
world is valid.

A DTD can be declared inline inside an XML document, or as an external reference.


Internal DTD Declaration
If the DTD is declared inside the XML file, it should be wrapped in a DOCTYPE definition with the
following syntax:

<!DOCTYPE root-element [element-declarations]>

Example XML document with an internal DTD:


<?xml version="1.0"?>
<!DOCTYPE note [
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend</body>
</note>

The DTD above is interpreted like this:

of type "#PCDATA"

External DTD Declaration


If the DTD is declared in an external file, it should be wrapped in a DOCTYPE definition with the
following syntax:
<!DOCTYPE root-element SYSTEM "filename">

This is the same XML document as above, but with an external DTD:

<?xml version="1.0"?>
<!DOCTYPE note SYSTEM "note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

And this is the file "note.dtd" which contains the DTD:


<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>

The Building Blocks of XML Documents


Seen from a DTD point of view, all XML documents (and HTML documents) are made up by the
following building blocks:

Attributes
Elements
Elements are the main building blocks of both XML and HTML documents. Examples of HTML
elements are "body" and "table". Examples of XML elements could be "note" and "message".
Elements can contain text, other elements, or be empty. Examples of empty HTML elements are
"hr", "br" and "img".
Examples:
<body>some text</body>
<message>some text</message>

Attributes
Attributes provide extra information about elements. Attributes are always placed inside the opening
tag of an element. Attributes always come in name/value pairs. The following "img" element has
additional information about a source file:
<img src="computer.gif" />

The name of the element is "img". The name of the attribute is "src". The value of the attribute is
"computer.gif". Since the element itself is empty it is closed by a " /".

Entities
Some characters have a special meaning in XML, like the less than sign (<) that defines the start of
an XML tag. Most of you know the HTML entity: "&nbsp;". This "no-breaking-space" entity is used
in HTML to insert an extra space in a document. Entities are expanded when a document is parsed
by an XML parser.

The following entities are predefined in XML:


Entity References Character
&lt; <
&gt; >
&amp; &
&quot; "
&apos; '

PCDATA
PCDATA means parsed character data. Think of character data as the text found between the start
tag and the end tag of an XML element. PCDATA is text that WILL be parsed by a parser. The text
will be examined by the parser for entities and markup.
Tags inside the text will be treated as markup and entities will be expanded. However, parsed
character data should not contain any &, <, or > characters; these need to be represented by the
&amp; &lt; and &gt; entities, respectively.

CDATA
CDATA means character data. CDATA is text that will NOT be parsed by a parser. Tags inside the
text will NOT be treated as markup and entities will not be expanded.
DTD Elements
In a DTD, elements are declared with an ELEMENT declaration.
Declaring Elements
In a DTD, XML elements are declared with an element declaration with the following syntax:
<!ELEMENT element-name category> or <!ELEMENT element-name (element-content)>

Empty Elements
Empty elements are declared with the category keyword EMPTY:
<!ELEMENT element-name EMPTY>
Example: <!ELEMENT br EMPTY>
XML example: <br />

Elements with Parsed Character Data


Elements with only parsed character data are declared with #PCDATA inside parentheses:
<!ELEMENT element-name (#PCDATA)>
Example: <!ELEMENT from (#PCDATA)>

Elements with any Contents


Elements declared with the category keyword ANY, can contain any combination of parsable data:
<!ELEMENT element-name ANY>
Example:
<!ELEMENT note ANY>

Elements with Children (sequences)


Elements with one or more children are declared with the name of the children elements inside
parentheses:
<!ELEMENT element-name (child1)>
or
<!ELEMENT element-name (child1,child2,...)>
Example:
<!ELEMENT note (to,from,heading,body)>
When children are declared in a sequence separated by commas, the children must appear in the
same sequence in the document. In a full declaration, the children must also be declared, and the
children can also have children. The full declaration of the "note" element is:
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>

Declaring Only One Occurrence of an Element


<!ELEMENT element-name (child-name)>
Example:
<!ELEMENT note (message)>
The example above declares that the child element "message" must occur once, and only once inside
the "note" element.

Declaring Minimum One Occurrence of an Element


<!ELEMENT element-name (child-name+)>
Example:
<!ELEMENT note (message+)>
The + sign in the example above declares that the child element "message" must occur one or more
times inside the "note" element.

Declaring Zero or More Occurrences of an Element


<!ELEMENT element-name (child-name*)>
Example:
<!ELEMENT note (message*)>
The * sign in the example above declares that the child element "message" can occur zero or more
times inside the "note" element.

Declaring Zero or One Occurrences of an Element


<!ELEMENT element-name (child-name?)>
Example:
<!ELEMENT note (message?)>
The ? sign in the example above declares that the child element "message" can occur zero or one
time inside the "note" element.

Declaring either/or Content


Example:
<!ELEMENT note (to,from,header,(message|body))>
The example above declares that the "note" element must contain a "to" element, a "from" element, a
"header" element, and either a "message" or a "body" element.

Declaring Mixed Content


Example:
<!ELEMENT note (#PCDATA|to|from|header|message)*>
The example above declares that the "note" element can contain zero or more occurrences of parsed
character data, "to", "from", "header", or "message" elements.

DTD Attributes
In the DTD, XML element attributes are declared with an ATTLIST declaration. An attribute
declaration has the following syntax:
<!ATTLIST element-name attribute-name attribute-type default-value>
DTD example:
<!ATTLIST payment type CDATA "check">
XML example:
<payment type="check" />
Some attribute-types are:

Type Description
CDATA The value is character data
(en1|en2|..) The value must be one from an enumerated list
ID The value is a unique id

The default-value can be one of the following:


Value Explanation
Value The default value of the attribute
#REQUIRED The attribute is required
#IMPLIED The attribute is not required
#FIXED value An attribute value is fixed

A Default Attribute Value


DTD:
<!ELEMENT square EMPTY>
<!ATTLIST square width CDATA "0">
Valid XML:
<square width="100" />

In the example above, the "square" element is defined to be an empty element with a "width"
attribute of type CDATA. If no width is specified, it has a default value of 0.

#REQUIRED
Syntax
<!ATTLIST element-name attribute-name attribute-type #REQUIRED>
Example
DTD:
<!ATTLIST person number CDATA #REQUIRED>

Valid XML:
<person number="5677" />
Invalid XML:
<person />

Use the #REQUIRED keyword if you don't have an option for a default value, but still want to force
the attribute to be present.

#IMPLIED
Syntax
<!ATTLIST element-name attribute-name attribute-type #IMPLIED>
Example
DTD:
<!ATTLIST contact fax CDATA #IMPLIED>
Valid XML:
<contact fax="555-667788" />
Valid XML:
<contact />
Use the #IMPLIED keyword if you don't want to force the author to include an attribute, and you
don't have an option for a default value.

#FIXED
Syntax
<!ATTLIST element-name attribute-name attribute-type #FIXED "value">
Example
DTD:
<!ATTLIST sender company CDATA #FIXED "Microsoft">
Valid XML:
<sender company="Microsoft" />
Invalid XML:
<sender company="W3Schools" />
Use the #FIXED keyword when you want an attribute to have a fixed value without allowing the
author to change it. If an author includes another value, the XML parser will return an error.

Enumerated Attribute Values


Syntax
<!ATTLIST element-name attribute-name (en1|en2|..) default-value>
Example
DTD:
<!ATTLIST payment type (check|cash) "cash">
XML example:
<payment type="check" />
or
<payment type="cash" />
Use enumerated attribute values when you want the attribute value to be one of a fixed set of legal
values.

DTD Newspaper Example


<!DOCTYPE NEWSPAPER [
<!ELEMENT NEWSPAPER (ARTICLE+)>
<!ELEMENT ARTICLE (HEADLINE,BYLINE,LEAD,BODY,NOTES)>
<!ELEMENT HEADLINE (#PCDATA)>
<!ELEMENT BYLINE (#PCDATA)>
<!ELEMENT LEAD (#PCDATA)>
<!ELEMENT BODY (#PCDATA)>
<!ELEMENT NOTES (#PCDATA)>
<!ATTLIST ARTICLE AUTHOR CDATA #REQUIRED>
]>

5.6 XSD Simple Types, XSD Attributes;


XML Schema is an XML-based alternative to DTD which describes the structure of an XML
document. The XML Schema language is also referred to as XML Schema Definition (XSD). XML
Schema became a W3C‘s recommendation in 02, May 2001.
What is an XML Schema?
The purpose of an XML Schema is to define the legal building blocks of an XML document, just
like a DTD.
An XML Schema:

d elements

ibutes

XML Schemas are the Successors of DTDs


XML Schemas are used in most Web applications as a replacement for DTDs. Reasons for
replacement include: extensible to future additions, richer and more powerful than DTDs, support
data types and support namespaces.

Example before discussion:


Look at this simple XML document called "note.xml":
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
We have already written a DTD for this xml. Its turn now for XSD:
The following example is an XML Schema file called "note.xsd" that defines the elements of the
XML document above ("note.xml"):
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.a.com"
xmlns=http://www.a.com‖ elementFormDefault="qualified">

<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

Let‘s elaborate XSD document above (note.xsd):


The <schema> Element
The <schema> element is the root element of every XML Schema:
<?xml version="1.0"?>
<xs:schema>
... ...
</xs:schema>
The <schema> element may contain some attributes. A schema declaration often looks something
like this:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.a.com" xmlns="http://www.a.com"
elementFormDefault="qualified">
... ...
</xs:schema>
The following fragment:
xmlns:xs="http://www.w3.org/2001/XMLSchema" indicates that the elements and data types used in
the schema come from the "http://www.w3.org/2001/XMLSchema" namespace. It also specifies that
the elements and data types that come from the "http://www.w3.org/2001/XMLSchema" namespace
should be prefixed with xs:
This fragment:
targetNamespace="http://www.a.com" indicates that the elements defined by this schema (note, to,
from, heading, body.) come from the "http://www.a.com" namespace.
This fragment:
xmlns="http://www.a.com" indicates that the default namespace is "http://www.a.com".
This fragment:
elementFormDefault="qualified" indicates that any elements used by the XML instance document
which were declared in this schema must be namespace qualified.

Referencing a Schema in an XML Document


This XML document has a reference to an XML Schema:
<?xml version="1.0"?>
<note xmlns="http://www.a.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.a.com note.xsd">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
The following fragment:
xmlns="http://www.a.com" specifies the default namespace declaration. This declaration tells the
schema-validator that all the elements used in this XML document are declared in the
"http://www.a.com" namespace.
Once you have the XML Schema Instance namespace available:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance", you can use the schema Location
attribute. This attribute has two values, separated by a space. The first value is the namespace to use.
The second value is the location of the XML schema to use for that namespace:
xsi:schemaLocation=http://www.a.com note.xsd

XSD: Simple Types


XML Schemas define the elements of your XML files. A simple element is an XML element that
contains only text. It cannot contain any other elements or attributes. However, the "only text"
restriction is quite misleading. The text can be of many different types. It can be one of the types
included in the XML Schema definition (boolean, string, date, etc.), or it can be a custom type that
you can define yourself. You can also add restrictions (facets) to a data type in order to limit its
content, or you can require the data to match a specific pattern.
Defining a Simple Element
The syntax for defining a simple element is:
<xs:element name="xxx" type="yyy"/>
where xxx is the name of the element and yyy is the data type of the element.
XML Schema has a lot of built-in data types. The most common types are:
xs:string
xs:decimal
xs:integer
xs:boolean
xs:date
xs:time
Example
Here are some XML elements:
<lastname>Refsnes</lastname>
<age>32</age>
<dateborn>1982-08-21</dateborn>
And here are the corresponding simple element definitions:
<xs:element name="lastname" type="xs:string"/>
<xs:element name="age" type="xs:integer"/>
<xs:element name="dateborn" type="xs:date"/>
Default and Fixed Values for Simple Elements
Simple elements may have a default value OR a fixed value specified. A default value is
automatically assigned to the element when no other value is specified. In the following example the
default value is "red":
<xs:element name="color" type="xs:string" default="red"/>
A fixed value is also automatically assigned to the element, and you cannot specify another
value. In the following example the fixed value is "red":
<xs:element name="color" type="xs:string" fixed="red"/>

XSD Attribute
Simple elements cannot have attributes. If an element has attributes, it is considered to be of a
complex type. But the attribute itself is always declared as a simple type.
The syntax for defining an attribute is:
<xs:attribute name="xxx" type="yyy"/>
where xxx is the name of the attribute and yyy specifies the data type of the attribute.

Example: Here is an XML element with an attribute:


<lastname lang="EN">Smith</lastname>
And here is the corresponding attribute definition:
<xs:attribute name="lang" type="xs:string"/>

Default and Fixed Values for Attributes


Attributes may have a default value OR a fixed value specified. A default value is automatically
assigned to the attribute when no other value is specified. In the following example the default value
is "EN":
<xs:attribute name="lang" type="xs:string" default="EN"/>
A fixed value is also automatically assigned to the attribute, and you cannot specify another value. In
the following example the fixed value is "EN":
<xs:attribute name="lang" type="xs:string" fixed="EN"/>

Optional and Required Attributes


Attributes are optional by default. To specify that the attribute is required, use the "use"
attribute:
<xs:attribute name="lang" type="xs:string" use="required"/>

Restrictions on Content
When an XML element or attribute has a data type defined, it puts restrictions on the element's or
attribute's content. If an XML element is of type "xs:date" and contains a string like "Hello World",
the element will not validate. With XML Schemas, you can also add your own restrictions to your
XML elements and attributes. These restrictions are called facets.
Facets/XML Restrictions
Restrictions are used to define acceptable values for XML elements or attributes. Restrictions on
XML elements are called facets.
Restrictions for Datatypes
Constraint Description
enumeration Defines a list of acceptable values
fractionDigits
Specifies the maximum number of decimal places allowed. Must be equal to or
greater than zero
Length Specifies the exact number of characters or list items allowed. Must be equal to or
greater than zero
maxExclusive Specifies the upper bounds for numeric values (the value must be less than this
value)
maxInclusive Specifies the upper bounds for numeric values (the value must be less than or
equal to this value)
maxLength Specifies the maximum number of characters or list items allowed. Must be equal
to or greater than zero
minExclusive Specifies the lower bounds for numeric values (the value must be greater than this
value)
minInclusive Specifies the lower bounds for numeric values (the value must be greater than or
equal to this value)
minLength Specifies the minimum number of characters or list items allowed. Must be equal
to or greater than zero
Pattern Defines the exact sequence of characters that are acceptable
totalDigits Specifies the exact number of digits allowed. Must be greater than zero
whiteSpace Specifies how white space (line feeds, tabs, spaces, and carriage returns) is
handled

Restrictions on Values
The following example defines an element called "age" with a restriction. The value of age cannot be
lower than 0 or greater than 120:
<xs:element name="age">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="0"/>
<xs:maxInclusive value="120"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

Restrictions on a Set of Values


To limit the content of an XML element to a set of acceptable values, we would use the enumeration
constraint.
The example below defines an element called "car" with a restriction. The only acceptable values
are:
Audi, Golf, BMW:
<xs:element name="car">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Audi"/>
<xs:enumeration value="Golf"/>
<xs:enumeration value="BMW"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

Restrictions on a Series of Values


To limit the content of an XML element to define a series of numbers or letters that can be used, we
would use the pattern constraint.
The example below defines an element called "letter" with a restriction. The only acceptable value is
ONE of the LOWERCASE letters from a to z:

<xs:element name="letter">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[a-z]"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

The next example defines an element called "initials" with a restriction. The only acceptable value is
THREE of the UPPERCASE letters from a to z:
<xs:element name="initials">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[A-Z][A-Z][A-Z]"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

The next example also defines an element called "initials" with a restriction. The only acceptable
value
is THREE of the LOWERCASE OR UPPERCASE letters from a to z:
<xs:element name="initials">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[a-zA-Z][a-zA-Z][a-zA-Z]"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

The next example defines an element called "choice" with a restriction. The only acceptable value is
ONE of the following letters: x, y, OR z:
<xs:element name="choice">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[xyz]"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

The next example defines an element called "prodid" with a restriction. The only acceptable value is
FIVE digits in a sequence, and each digit must be in a range from 0 to 9:
<xs:element name="prodid">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9][0-9][0-9][0-9][0-9]"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

Other Restrictions on a Series of Values


The example below defines an element called "letter" with a restriction. The acceptable value is zero
or more occurrences of lowercase letters from a to z:
<xs:element name="letter">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="([a-z])*"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

The next example also defines an element called "letter" with a restriction. The acceptable value is
one or more pairs of letters, each pair consisting of a lower case letter followed by an upper case
letter.
For example, "sToP" will be validated by this pattern, but not "Stop" or "STOP" or "stop":
<xs:element name="letter">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="([a-z][A-Z])+"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

The next example defines an element called "gender" with a restriction. The only acceptable value is
male OR female:
<xs:element name="gender">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="male|female"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

The next example defines an element called "password" with a restriction. There must be exactly
eight characters in a row and those characters must be lowercase or uppercase letters from a to z, or a
number from 0 to 9:

<xs:element name="password">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[a-zA-Z0-9]{8}"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

Restrictions on Whitespace Characters


To specify how whitespace characters should be handled, we would use the whiteSpace
constraint.This example defines an element called "address" with a restriction. The whiteSpace
constraint is set to "preserve", which means that the XML processor WILL NOT remove any white
space characters:
<xs:element name="address">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:whiteSpace value="preserve"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

This example also defines an element called "address" with a restriction. The whiteSpace constraint
is set to "replace", which means that the XML processor WILL REPLACE all white space characters
(line feeds, tabs, spaces) with spaces:
<xs:element name="address">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:whiteSpace value="replace"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
This example also defines an element called "address" with a restriction. The whiteSpace constraint
is set to "collapse", which means that the XML processor WILL REMOVE all white space haracters
(line feeds, tabs, spaces, carriage returns are replaced with spaces, leading and trailing spaces are
removed, and multiple spaces are reduced to a single space):
<xs:element name="address">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:whiteSpace value="collapse"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

Restrictions on Length
To limit the length of a value in an element, we would use the length, maxLength, and minLength
constraints.
This example defines an element called "password" with a restriction. The value must be exactly
eight characters:
<xs:element name="password">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:length value="8"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

This example defines another element called "password" with a restriction. The value must be
minimum five characters and maximum eight characters:

<xs:element name="password">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="5"/>
<xs:maxLength value="8"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

XSD Complex Types;


What is a Complex Element?
A complex element is an XML element that contains other elements and/or attributes.
There are four kinds of complex elements:

<product pid="1345"/>
<employee>
<firstname>John</firstname>
<lastname>Smith</lastname>
</employee>

<food type="dessert">Ice cream</food>

<description>
It happened on <date lang="norwegian">03.03.99</date> ....
</description>

Note: Each of these elements may contain attributes as well!

How to Define a Complex Element?


Look at this complex XML element, "employee", which contains only other elements:
<employee>
<firstname>John</firstname>
<lastname>Smith</lastname>
</employee>

We can define a complex element in an XML Schema two different ways:


1. The "employee" element can be declared directly by naming the element, like this:
<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
If you use the method described above, only the "employee" element can use the specified complex
type. Note that the child elements, "firstname" and "lastname", are surrounded by the <sequence>
indicator. This means that the child elements must appear in the same order as they are declared.

2. The "employee" element can have a type attribute that refers to the name of the complex type to
use:
<xs:element name="employee" type="personinfo"/>
<xs:complexType name="personinfo">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
If you use the method described above, several elements can refer to the same complex type, like
this:

<xs:element name="employee" type="personinfo"/>


<xs:element name="student" type="personinfo"/>
<xs:element name="member" type="personinfo"/>
<xs:complexType name="personinfo">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>

You can also base a complex element on an existing complex element and add some elements, like
this:
<xs:element name="employee" type="fullpersoninfo"/>
<xs:complexType name="personinfo">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="fullpersoninfo">
<xs:complexContent>
<xs:extension base="personinfo">
<xs:sequence>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>

How to define Complex Empty Elements?


An empty XML element:
<product prodid="1345" />
The "product" element above has no content at all. To define a type with no content, you can use
following format:
<xs:element name="product">
<xs:complexType>
<xs:attribute name="prodid" type="xs:positiveInteger"/>
</xs:complexType>
</xs:element>

How to define Text Only Elements?


Here is an example of an XML element, "shoesize", that contains text-only:
<shoesize country="france">35</shoesize>
The following example declares a complexType, "shoesize". The content is defined as an integer
value, and the "shoesize" element also contains an attribute named "country":
<xs:element name="shoesize">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:integer">
<xs:attribute name="country" type="xs:string" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>

How to define Complex Types with Mixed Content?


An XML element, "letter", that contains both text and other elements:
<letter>
Dear Mr.<name>John Smith</name>.
Your order <orderid>1032</orderid>
will be shipped on <shipdate>2001-07-13</shipdate>.
</letter>

The following schema declares the "letter" element:


<xs:element name="letter">
<xs:complexType mixed="true">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="orderid" type="xs:positiveInteger"/>
<xs:element name="shipdate" type="xs:date"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Note: To enable character data to appear between the child-elements of "letter", the mixed attribute
must be set to "true". The <xs:sequence> tag means that the elements defined (name, orderid and
shipdate) must appear in that order inside a "letter" element.
We could also give the complexType element a name, and let the "letter" element have a type
attribute that refers to the name of the complexType (if you use this method, several elements can
refer to the same complex type):
<xs:element name="letter" type="lettertype"/>
<xs:complexType name="lettertype" mixed="true">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="orderid" type="xs:positiveInteger"/>
<xs:element name="shipdate" type="xs:date"/>
</xs:sequence>
</xs:complexType>

XSD Indicators
We can control HOW elements are to be used in documents with indicators. There are seven
indicators:
Order indicators:

Occurrence indicators:

Group indicators:

Order Indicators
Order indicators are used to define the order of the elements.
All Indicator
The <all> indicator specifies that the child elements can appear in any order, and that each child
element must occur only once:
<xs:element name="person">
<xs:complexType>
<xs:all>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:all>
</xs:complexType>
</xs:element>

Note: When using the <all> indicator you can set the <minOccurs> indicator to 0 or 1 and the
<maxOccurs> indicator can only be set to 1.

Choice Indicator
The <choice> indicator specifies that either one child element or another can occur:
<xs:element name="person">
<xs:complexType>
<xs:choice>
<xs:element name="employee" type="employee"/>
<xs:element name="member" type="member"/>
</xs:choice>
</xs:complexType>
</xs:element>

Sequence Indicator
The <sequence> indicator specifies that the child elements must appear in a specific order:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

Occurrence Indicators
Occurrence indicators are used to define how often an element can occur.
Note: For all "Order" and "Group" indicators (any, all, choice, sequence, group name, and group
reference) the default value for maxOccurs and minOccurs is 1.
maxOccurs Indicator
The <maxOccurs> indicator specifies the maximum number of times an element can occur:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string" maxOccurs="10"/>
</xs:sequence>
</xs:complexType>
</xs:element>

The example above indicates that the "child_name" element can occur a minimum of one time (the
default value for minOccurs is 1) and a maximum of ten times in the "person" element.

minOccurs Indicator
The <minOccurs> indicator specifies the minimum number of times an element can occur:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string"
maxOccurs="10" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>

The example above indicates that the "child_name" element can occur a minimum of zero times and
a maximum of ten times in the "person" element.
Note: To allow an element to appear an unlimited number of times, use the
maxOccurs="unbounded" statement:

A working example:
An XML file called "Myfamily.xml":
<?xml version="1.0" encoding="ISO-8859-1"?>
<persons xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="family.xsd">
<person>
<full_name>Hege Refsnes</full_name>
<child_name>Cecilie</child_name>
</person>
<person>
<full_name>Tove Refsnes</full_name>
<child_name>Hege</child_name>
<child_name>Stale</child_name>
<child_name>Jim</child_name>
<child_name>Borge</child_name>
</person>
<person>
<full_name>Stale Refsnes</full_name>
</person>
</persons>

The XML file above contains a root element named "persons". Inside this root element we have
defined three "person" elements. Each "person" element must contain a "full_name" element and it
can contain up to five "child_name" elements.

Here is the schema file "family.xsd":


<?xml version="1.0" encoding="ISO-8859-1"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:element name="persons">
<xs:complexType>
<xs:sequence>
<xs:element name="person" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string"
minOccurs="0" maxOccurs="5"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

Group Indicators
Group indicators are used to define related sets of elements.

Element Groups
Element groups are defined with the group declaration, like this:
<xs:group name="groupname">
...
</xs:group>

You must define an all, choice, or sequence element inside the group declaration. The following
example defines a group named "persongroup", that defines a group of elements that must occur in
an exact sequence:
<xs:group name="persongroup">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
<xs:element name="birthday" type="xs:date"/>
</xs:sequence>
</xs:group>

After you have defined a group, you can reference it in another definition, like this:
<xs:group name="persongroup">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
<xs:element name="birthday" type="xs:date"/>
</xs:sequence>
</xs:group>
<!—Just like inheritance in oop -- >
<xs:element name="person" type="personinfo"/> <!—Empty tag, self closed -->
<xs:complexType name="personinfo">
<xs:sequence>
<xs:group ref="persongroup"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:complexType>

Attribute Groups
Attribute groups are defined with the attributeGroup declaration, like this:
<xs:attributeGroup name="groupname">
...
</xs:attributeGroup>

The following example defines an attribute group named "personattrgroup":


<xs:attributeGroup name="personattrgroup">
<xs:attribute name="firstname" type="xs:string"/>
<xs:attribute name="lastname" type="xs:string"/>
<xs:attribute name="birthday" type="xs:date"/>
</xs:attributeGroup>

After you have defined an attribute group, you can reference it in another definition, like this:
<xs:attributeGroup name="personattrgroup">
<xs:attribute name="firstname" type="xs:string"/>
<xs:attribute name="lastname" type="xs:string"/>
<xs:attribute name="birthday" type="xs:date"/>
</xs:attributeGroup>
<xs:element name="person">
<xs:complexType>
<xs:attributeGroup ref="personattrgroup"/>
</xs:complexType>
</xs:element>

The <any> Element


The <any> element enables us to extend the XML document with elements not specified by the
schema!
The following example is a fragment from an XML schema called "family.xsd". It shows a
declaration for the "person" element. By using the <any> element we can extend (after <lastname>)
the content of "person" with any element:

<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
<xs:any minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Now we want to extend the "person" element with a "children" element. In this case we can do so,
even if the author of the schema above never declared any "children" element.
Look at this schema file, called "children.xsd":
<?xml version="1.0" encoding="ISO-8859-1"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3schools.com"
xmlns="http://www.w3schools.com"
elementFormDefault="qualified">

<xs:element name="children">
<xs:complexType>
<xs:sequence>
<xs:element name="childname" type="xs:string"
maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

The XML file below (called "Myfamily.xml"), uses components from two different schemas;
"family.xsd" and "children.xsd":

<?xml version="1.0" encoding="ISO-8859-1"?>


<persons xmlns="http://www.microsoft.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.microsoft.com family.xsd
http://www.w3schools.com children.xsd">
<person>
<firstname>Hege</firstname>
<lastname>Refsnes</lastname>
<children>
<childname>Cecilie</childname>
</children>
</person>
<person>
<firstname>Stale</firstname>
<lastname>Refsnes</lastname>
</person>
</persons>

The XML file above is valid because the schema "family.xsd" allows us to extend the "person"
element with an optional element after the "lastname" element.
The <any> and <anyAttribute> elements are used to make EXTENSIBLE documents! They allow
documents to contain additional elements that are not declared in the main XML schema.

5.7 XML Style Sheets (XSLT), Xquery

XPath
XPath is used to navigate through elements and attributes in an XML document. XPath is a major
element in W3C's XSLT standard - and XQuery is built on XPath expressions.

What is XPath?

is a W3C recommendation

Major use of XPath: XPath is a language for finding information in an XML document.

XPath Terminology
Nodes
In XPath, there are seven kinds of nodes: element, attribute, text, namespace, rocessinginstruction,
comment, and document nodes. XML documents are treated as trees of nodes. The topmost element
of the tree is called the root element.
Let‘s begin with example:
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book>
<title lang="en">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="en">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>

Example of nodes in the XML document above:


<bookstore> (root element node)
<price>J K. Rowling</price> (element node)
lang="en" (attribute node)

Selecting Nodes
XPath uses path expressions to select nodes in an XML document. The node is selected by following
a path or steps. The most useful path expressions are listed below:

Expression Description
nodename Selects all nodes with the name "nodename"
/ Selects from the root node
// Selects nodes in the document from the current node that match the selection no
matter where they are
. Selects the current node
.. Selects the parent of the current node
@ Selects attributes

In the table below we have listed some path expressions and the result of the expressions:

Path Expression Result


bookstore Selects all nodes with the name "bookstore"

/bookstore Selects the root element bookstore


Note: If the path starts with a slash ( / ) it always represents an
absolute path to an element!
bookstore/book Selects all book elements that are children of bookstore

//book Selects all book elements no matter where they are in the document
bookstore//book Selects all book elements that are descendant of the bookstore
element, no matter where they are under the bookstore element
//@lang Selects all attributes that are named lang

Predicates
Predicates are used to find a specific node or a node that contains a specific value. Predicates are
always embedded in square brackets.
In the table below we have listed some path expressions with predicates and the result of the
expressions:

Path Expression Result

/bookstore/book[1] Note: IE5 and later has implemented that [0] should
be the first node, but according to the W3C standard
it should have been [1]!!
/bookstore/book[last()] Selects the last book element that is the child of the
bookstore element
/bookstore/book[last()-1] Selects the last but one book element that is the child
of the bookstore element
/bookstore/book[position()<3] Selects the first two book elements that are children
of the bookstore element
//title[@lang] Selects all the title elements that have an attribute
named lang
//title[@lang='eng'] Selects all the title elements that have an attribute
named lang with a value of 'eng'
/bookstore/book[price>35.00] Selects all the book elements of the bookstore
element that have a price element with a value greater
than 35.00
/bookstore/book[price>35.00]/title Selects all the title elements of the book elements of
the bookstore element that have a price element with
a value greater than 35.00

Selecting Unknown Nodes


XPath wildcards can be used to select unknown XML elements.

Wildcard Description
* Matches any element node
@* Matches any attribute node
node() Matches any node of any kind

In the table below we have listed some path expressions and the result of the expressions:

Path Expression Result


/bookstore/* Selects all the child nodes of the bookstore element.
//* Selects all elements in the document.
//title[@*] selects all title elements which have any attribute.

5.8 XQuery
XQuery is a language for finding and extracting elements and attributes from XML documents.
It is to XML what SQL is to database tables and is designed to query XML data.

tabases

XQuery Uses
XQuery can be used to:

Transform XML data to XHTML

XQuery Example:
for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title
Let‘s start with example:
"books.xml":
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
How to Select Nodes From "books.xml"?
Functions
XQuery uses functions to extract data from XML documents.
The doc() function is used to open the "books.xml" file:
doc("books.xml")

Path Expressions
XQuery uses path expressions to navigate through elements in an XML document.
The following path expression is used to select all the title elements in the "books.xml" file:
doc("books.xml")/bookstore/book/title

(/bookstore selects the bookstore element, /book selects all the book elements under the bookstore
element, and /title selects all the title elements under each book element)

The XQuery above will extract the following:


<title lang="en">Everyday Italian</title>
<title lang="en">Harry Potter</title>
<title lang="en">XQuery Kick Start</title>
<title lang="en">Learning XML</title>

Predicates
XQuery uses predicates to limit the extracted data from XML documents.
The following predicate is used to select all the book elements under the bookstore element that have
a price element with a value that is less than 30:
doc("books.xml")/bookstore/book[price<30]

The XQuery above will extract the following:


<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>

FLWOR Expressions
FLWOR is an acronym for "For, Let, Where, Order by, Return".
Example:
for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title
Above xquery generates following output:
<title lang="en">Learning XML</title>
<title lang="en">XQuery Kick Start</title>

Explanation:
The for clause selects all book elements under the bookstore element into a variable called $x.
The let clause simply declares a variable and gives it a value:

Example:
let $maxCredit := 3000
let $overdrawnCustomers := //customer[overdraft > $maxCredit]
return count($overdrawnCustomers)

The where clause selects only book elements with a price element with a value greater than 30.
The order by clause defines the sort-order. Will be sort by the title element.
The return clause specifies what should be returned. Here it returns the title elements.

Another Example:
for $x in doc("books.xml")/bookstore/book
return if ($x/@category="CHILDREN")
then <child>{data($x/title)}</child>
else <adult>{data($x/title)}</adult>
Output:
<adult>Everyday Italian</adult>
<child>Harry Potter</child>
<adult>XQuery Kick Start</adult>
<adult>Learning XML</adult>

FLWOR + HTML

Present the Result in an HTML List

Look at the following XQuery FLWOR expression:


for $x in doc("books.xml")/bookstore/book/title
order by $x
return $x
The expression above will select all the title elements under the book elements that are under the
bookstore element, and return the title elements in alphabetical order.
Now we want to list all the book-titles in our bookstore in an HTML list. We add <ul> and <li> tags
to the FLWOR expression:

<ul>
{
for $x in doc("books.xml")/bookstore/book/title
order by $x
return <li>{$x}</li>
}
</ul>
The result of the above will be:
<ul>
<li><title lang="en">Everyday Italian</title></li>
<li><title lang="en">Harry Potter</title></li>
<li><title lang="en">Learning XML</title></li>
<li><title lang="en">XQuery Kick Start</title></li>
</ul>

Now we want to eliminate the title element, and show only the data inside the title element:
<ul>
{
for $x in doc("books.xml")/bookstore/book/title
order by $x
return <li>{data($x)}</li>
}
</ul>
The result will be (an HTML list):
<ul>
<li>Everyday Italian</li>
<li>Harry Potter</li>
<li>Learning XML</li>
<li>XQuery Kick Start</li>
</ul>
5.7 XSL/XSLT
XSL stands for EXtensible Stylesheet Language, and is a style sheet language for XML documents.
XSLT stands for XSL Transformations. In this section you will learn how to use XSLT to transform
XML documents into other formats, like XHTML.

It Started with XSL


The World Wide Web Consortium (W3C) started to develop XSL because there was a need for an
XML-based Stylesheet Language.

CSS = Style Sheets for HTML


HTML uses predefined tags, and the meaning of each tag is well understood.
The <table> tag in HTML defines a table - and a browser knows how to display it.
Adding styles to HTML elements are simple. Telling a browser to display an element in a special
font or color is easy with CSS.

XSL = Style Sheets for XML


XML does not use predefined tags (we can use any tag-names we like), and therefore the meaning of
each tag is not well understood.
A <table> tag could mean an HTML table, a piece of furniture, or something else - and a
browser does not know how to display it.
XSL describes how the XML document should be displayed!

XSL - More Than a Style Sheet Language


XSL consists of three parts:
- a language for transforming XML documents
- a language for navigating in XML documents
-FO - a language for formatting XML documents

What is XSLT?

XSLT = XSL Transformations


XSLT is the most important part of XSL.

XSLT is used to transform an XML document into another XML document, or another type of
document that is recognized by a browser, like HTML and XHTML. Normally XSLT does this by
transforming each XML element into an (X)HTML element.
With XSLT you can add/remove elements and attributes to or from the output file. You can also re-
arrange and sort elements, perform tests and make decisions about which elements to hide and
display, and a lot more.
A common way to describe the transformation process is to say that XSLT transforms an XML
source-tree into an XML result-tree.

XSLT Uses XPath


XSLT uses XPath to find information in an XML document. XPath is used to navigate through
elements and attributes in XML documents.

How Does it Work?


In the transformation process, XSLT uses XPath to define parts of the source document that should
match one or more predefined templates. When a match is found, XSLT will transform the matching
part of the source document into the result document.
XSLT Example
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Save this file with .xsl extension, say cdcatalog.xsl


And we can reference this XSL style sheet to xml document as:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?>
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
.
.
</catalog>

The <xsl:template> Element


A template contains rules to apply when a specified node is matched. The <xsl:template> element is
used to build templates.
The match attribute is used to associate a template with an XML element. The match attribute can
also be used to define a template for the entire XML document. The value of the match attribute is
an XPath expression (i.e. match="/" defines the whole document).

The <xsl:value-of> Element


The <xsl:value-of> element can be used to extract the value of an XML element and add it to the
output stream of the transformation.
<td><xsl:value-of select="catalog/cd/title"/></td>
<td><xsl:value-of select="catalog/cd/artist"/></td>
Note: The select attribute, in the example above, contains an XPath expression.

The <xsl:for-each> Element


The XSL <xsl:for-each> element can be used to select every XML element of a specified node-set.
Filtering the Output
We can also filter the output from the XML file by adding a criterion to the select attribute in the
<xsl:for-each> element.
<xsl:for-each select="catalog/cd[artist='Bob Dylan']">
Legal filter operators are:

Example:
<xsl:for-each select="catalog/cd[artist='Bob Dylan']">
<tr>
<td>
<xsl:value-of select="title"/>
</td>
<td>
<xsl:value-of select="artist"/>
</td>
</tr>
</xsl:for-each>

<xsl:sort> Element
The <xsl:sort> element is used to sort the output.
To sort the output, simply add an <xsl:sort> element inside the <xsl:for-each> element in the XSL
file.
<xsl:for-each select="catalog/cd">
<xsl:sort select="artist"/>
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>

<xsl:if> Element
The <xsl:if> element is used to put a conditional test against the content of the XML
file. To add a conditional test, add the <xsl:if> element inside the <xsl:for-each> element in the XSL
file.
Syntax
<xsl:if test="expression">
...some output if the expression is true...
</xsl:if>
Example:
<xsl:for-each select="catalog/cd">
<xsl:if test="price &gt; 10">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
<td><xsl:value-of select="price"/></td>
</tr>
</xsl:if>
</xsl:for-each>

<xsl:choose> Element
The <xsl:choose> element is used in conjunction with <xsl:when> and
<xsl:otherwise> to express multiple conditional tests.
Syntax
<xsl:choose>
<xsl:when test="expression">
... some output ...
</xsl:when>
<xsl:otherwise>
... some output ....
</xsl:otherwise>
</xsl:choose>
To insert a multiple conditional test against the XML file, add the <xsl:choose>, <xsl:when>, and
<xsl:otherwise> elements to the XSL file.
Example
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<xsl:choose>
<xsl:when test="price &gt; 10">
<td bgcolor="#ff00ff">
<xsl:value-of select="artist"/></td>
</xsl:when>
<xsl:otherwise>
<td><xsl:value-of select="artist"/></td>
</xsl:otherwise>
</xsl:choose>
</tr>
</xsl:for-each>
Another Example
Here is another example that contains two <xsl:when> elements:
Example
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<xsl:choose>
<xsl:when test="price &gt; 10">
<td bgcolor="#ff00ff">
<xsl:value-of select="artist"/></td>
</xsl:when>
<xsl:when test="price &gt; 9">
<td bgcolor="#cccccc">
<xsl:value-of select="artist"/></td>
</xsl:when>
<xsl:otherwise>
<td><xsl:value-of select="artist"/></td>
</xsl:otherwise>
</xsl:choose>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Unit 6: Server Side Scripting using PHP (8 Hrs.)

PHP Syntax, Variables, Data Types , Strings, Constants, Operators, Control structure, Functions,
Array, Creating Class and Objects, PHP Forms, Accessing Form Elements, Form Validation.

Events, Cookies and Sessions, Working with PHP and MySQL, Connecting to Database, Creating,
Selecting, Deleting, Updating Records in a table, Inserting Multiple Data, Introduction to
CodeIgniter, Laravel, Wordpress etc.

Server-side scripting languages:

After the advent of CGI, multiple programming languages were evolved such as PHP, Python, Ruby,
ColdFusion, C#, Java, C++ and so on for server-side scripting among which some of them are
described below:

6.1 PHP: It is the most prevalent server-side language used on the web which was designed to
extract and manipulate information in the database. The language is used in association with SQL
language for the Database. It is used in Facebook, WordPress and Wikipedia.

Python: The language is fast and contains shorter code. It is good for beginners as it concentrates on
the readability and simplicity of the code. Python functions well in the object-oriented environment
and used in famous sites like Youtube, Google, etc.

Ruby: It contains complex logic which packages the back-end with database utility which can also
be provided by PHP and SQL.

Key Differences Between Server-side Scripting and Client-side Scripting

1. Server-side scripting is used at the backend, where the source code is not viewable or hidden
at the client side (browser). On the other hand, client-side scripting is used at the front end
which users can see from the browser.
2. When a server-side script is processed it communicates to the server. As against, client-side
scripting does not need any server interaction.
3. The client-side scripting language involves languages such as HTML, CSS and JavaScript. In
contrast, programming languages such as PHP, ASP.net, Ruby, ColdFusion, Python, C#, Java,
C++, etc.
4. Server-side scripting is useful in customizing the web pages and implements the dynamic
changes in the websites. Conversely, the client-side script can effectively minimize the load to
the server.
5. Server-side scripting is more secure than client-side scripting as the server side scripts are
usually hidden from the client end, while a client-side script is visible to the users.
6.1 PHP:
Introduction:

PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web
pages.

PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.

PHP 7 is the latest stable release.

What is PHP?
 PHP stands for PHP: Hypertext Preprocessor
 PHP is a server-side scripting language, like ASP
 PHP scripts are executed on the server
 PHP supports many databases (MySQL, Informix, Oracle, Sybase, etc.)
 PHP is open source software
What is a PHP File?
 PHP files can contain text, HTML tags and scripts
 PHP files are returned to the browser as plain HTML
 PHP files have a file extension of ".php"

Server Configurations:
PHP is a server side scripting language. The server we are using for the implementation of PHP is a
WAMP (―Windows, Apache, MySQL, and PHP) and the modified type of WAMP is a XAMPP [X
(may be Extended) Apache MySQL PHP Perl].
Download XAMPP from the following link: https://www.apachefriends.org/index.html
The word localhost is used in URLs to specify the local computer, which will also respond to the IP
address of 127.0.0.1, so you can use either method of calling up the document root of your web
server.

Accessing the document root


The document root is the directory that contains the main web documents for a domain. This is the
one that is entered when a basic URL without a path is typed into a browser, such as
http://yahoo.com or, for your local server, http://localhost. By default, XAMP uses the following
location for this directory: C:/xampp/htdocs to ensure that you have everything correctly configured,
you should now create the obligatory ―Hello World‖ file. So create a small HTML file along the
following lines using Windows Notepad or any other program or text editor, but not a rich word
processor such as Microsoft Word (unless you save as plain text).

After installing downloaded XAMPP, next step is to download Visual Studio Code (Vs Code) and
adding extensions supporting PHP programming. It depends on the choice of a developer, which
IDE to be used. There are so many IDE built that supports PHP code.

Another step is to add a directory to VS Code for the manipulation of PHP codes. For this, the
directory is added inside C:/Xampp/htdocs/FolderName.
Now, from VS code the ―FolderName‖ is opened and files ( html, php, css, js, etc.) can be added to
that folder.

Now, create a file called Test.php to the folder that is added from C:/xampp/htdocs and write the php
code.
6.1 Basic PHP Syntax
A PHP scripting block always starts with. A PHP scripting block can be placed anywhere in the
document. A PHP file normally contains HTML tags, just like an HTML file, and some PHP
scripting code.
Below, we have an example of a simple PHP script which sends the text "Hello World" to the
browser:

<html>
<head>
<title>Hello php</title>
</head>
<body>
<?php echo "<h2>Hello World</h2>" ?>
</body>
</html>

Each code line in PHP must end with a semicolon.


Note: The file must have a .php extension. If the file has a .html extension, the PHP code will not be
executed.
Comments in PHP
In PHP, we use // to make a single-line comment or /* and */ to make a large comment block.
<?php
//this is a single line comment
/* this is a
Multi line
Comment
*/
echo "<h2>Hello World</h2>"
?>

6.2 Variables in PHP:


Variables are used for storing values, like text strings, numbers or arrays. When a variable is set it
can be used over and over again in your script. All variables in PHP start with a $ sign symbol. The
correct way of setting a variable in PHP:

Example: Variables Declaration


<!DOCTYPE html>
<html>
<head>
<title>PHP VARIABLES</title>
</head>
<body>
<?php
$text = "Hello World";
$number = 100;
echo $text;
echo " ";
echo $number;
?>
</body>
</html>

PHP is a Loosely Typed Language In PHP a variable does not need to be declared before being set.
In the example above, you see that you do not have to tell PHP which data type the variable is. PHP
automatically converts the variable to the correct data type, depending on how they are set. In a
strongly typed programming language, you have to declare (define) the type and name of the
variable before using it. In PHP the variable is declared automatically when you use it.
Variable Naming Rules
 A variable name must start with a letter or an underscore "_"
 A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0- 9, and
_)
 A variable name should not contain spaces. If a variable name is more than one word, it should be
separated with underscore ($my_string), or with capitalization ($myString)
 Variable names are case-sensitive ($y and $Y are two different variables)

Strings in PHP
String variables are used for values that contain character strings. After we create a string we can
manipulate it. A string can be used directly in a function or it can be stored in a variable. The
Concatenation Operator for String There is only one string operator in PHP. The concatenation
operator (.) is used to put two string values together. To concatenate two variables together, use the
dot (.) operator.
Example:
<html>
<head>
<title>STRING CONCATENATION</title>
</head>
<body>
<?php
$txt1 = "Hello World";
$txt2 = "1234";
echo $txt1 . " " . $txt2;
?>
</body>
</html>
6.3 PHP Operators
Operators are used to perform operations on variables and values.

PHP divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators
 Conditional assignment operators

Operator Name Example Result


+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y'th power

PHP Assignment Operators

The PHP assignment operators are used with numeric values to write a value to a variable.

The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of
the assignment expression on the right.

Assignment Same as... Description


x=y x=y Value of y is assigned to x.
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus

PHP Comparison Operators:

Operator Name Example Result


== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === Returns true if $x is equal to $y, and they are of the same
$y type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== Returns true if $x is not equal to $y, or they are not of the
$y same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or $x >= $y Returns true if $x is greater than or equal to $y
equal to
<= Less than or $x <= $y Returns true if $x is less than or equal to $y
equal to
<=> Spaceship $x <=> Returns an integer less than, equal to, or greater than zero,
$y depending on if $x is less than, equal to, or greater than $y.
Introduced in PHP 7.

PHP Increment and Decrement Operators

Operator Name Description


++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one

PHP Logical Operators

Operator Name Example Result


and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true

PHP String Operators

Operator Name Example Result


. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2
.= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1

PHP Conditional Assignment Operators

Operator Name Example Result


?: Ternary $x Returns the value of $x.
= expr1 ? expr2 : expr3 The value of $x is expr2 if expr1 = TRUE.
The value of $x is expr3 if expr1 = FALSE
?? Null $x = expr1 ?? expr2 Returns the value of $x.
coalescing The value of $x is expr1 if expr1 exists, and
is not NULL.
If expr1 does not exist, or is NULL, the value
of $x is expr2.
Introduced in PHP 7
Control Structures:(Conditions and Loops)

PHP Conditional Statements

In PHP we have the following conditional statements:

 if statement - executes some code if one condition is true


 if...else statement - executes some code if a condition is true and another code if that
condition is false
 if...elseif...else statement - executes different codes for more than two conditions
 switch statement - selects one of many blocks of code to be executed

Example:
<!DOCTYPE html>
<html>
<body>
<?php
$t = date("H");
echo "<p>The hour (of the server) is " . $t;
echo ", and will give the following message:</p>";
if ($t < "10") { //if condition
echo "Have a good morning!";
} elseif ($t < "20") { //else if condition
echo "Have a good day!";
} else { //else condition
echo "Have a good night!";
}
?>
</body>
</html>
The PHP switch Statement

Use the switch statement to select one of many blocks of code to be executed.

<!DOCTYPE html>
<html>
<body>

<?php
$favcolor = "red";

switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>

</body>
</html>

PHP Loops

Often when you write code, you want the same block of code to run over and over again a certain
number of times. So, instead of adding several almost equal code-lines in a script, we can use loops.

Loops are used to execute the same block of code again and again, as long as a certain condition is
true.

In PHP, we have the following loop types:

 while - loops through a block of code as long as the specified condition is true
 do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array

The PHP while Loop

The while loop executes a block of code as long as the specified condition is true.

Syntax
while (condition is true) {
code to be executed;
}

Example:whileloop.php

<!DOCTYPE html>
<html>
<body>
<?php
$x = 1;
while ($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
</body>
</html>

The PHP do-while Loop


The do...while loop will always execute the block of code once, it will then check the condition, and
repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);

Example: do_whileloop.php
<body>
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
</body>

Similarly,
For loop:
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>

Foreach loop:

<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>

Foreach break and continue statements:


The break statement can also be used to jump out of a loop.

This example jumps out of the loop when x is equal to 4:

<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.

This example skips the value of 4:

Example
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>

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:

$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";

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 to create an array!

An array can hold many values under a single name, and you can access the values by referring to an
index number.
Example:

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";

foreach ($cars as $value) {


echo "$value <br>";
}
?>

Create an Array in PHP


In PHP, the array() function is used to create an array:
array();
In PHP, there are three types of arrays:
 Indexed arrays - Arrays with a numeric index
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
 Associative arrays - Arrays with named keys
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
The named keys can then be used in a script:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

 Multidimensional arrays - Arrays containing one or more arrays

A multidimensional array is an array containing one or more arrays.


PHP supports multidimensional arrays that are two, three, four, five, or more levels deep.
However, arrays more than three levels deep are hard to manage for most people.
The dimension of an array indicates the number of indices you need to select an element.
 For a two-dimensional array you need two indices to select an element
 For a three-dimensional array you need three indices to select an element

Two-Dimensional Array:
Name Stock Sold
Suzuki 22 18
Toyota 15 13
Maruti 5 2
Land Rover 17 15

We can store the data from the table above in a two-dimensional array, like this:
$cars = array (
array("Suzuki",22,18),
array("Toyota",15,13),
array("Maruti",5,2),
array("Land Rover",17,15)
);

Example:
<html>
<body>
<?php
$cars = array(
array("Volvo", 22, 18),
array("BMW", 15, 13),
array("Saab", 5, 2),
array("Land Rover", 17, 15)
);
echo $cars[0][0] . ":stock: " . $cars[0][1] . ",sold: ".$cars[0][2].".<br>";
echo $cars[1][0] . ":stock: " . $cars[1][1] . ",sold: ". $cars[1][2].".<br>";
echo $cars[2][0] . ":stock: " . $cars[2][1] . ",sold: ". $cars[2][2].".<br>";
echo $cars[3][0] . ":stock: " . $cars[3][1] . ",sold: ". $cars[3][2].".<br>";
?>
</body>
</html>
Using for loop for same solution:

<html>
<body>
<?php
$cars = array(
array("Volvo", 22, 18),
array("BMW", 15, 13),
array("Saab", 5, 2),
array("Land Rover", 17, 15)
);
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>" . $cars[$row][$col] . "</li>";
}
echo "</ul>";
}
?>
</body>
</html>
The count() function is used to return the length (the number of elements) of an array:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>

The sort() function is used to return the array in ascending numerical or aplhabetical order:
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
?>

Functions in PHP:

User Defined functions:

 A function is a block of statements that can be used repeatedly in a program.


 A function will not execute automatically when a page loads.
 A function will be executed by a call to the function.

A user-defined function declaration starts with the word function:

Syntax
function functionName() {
code to be executed;
}

Example:

<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
?>

Function Arguments:

<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}

familyName("Ram", "2050");
familyName("Shyam", "2060");
familyName("Hari", "2066");
?>

PHP is a Loosely Typed Language

In the example above, notice that we did not have to tell PHP which data type the variable is.

PHP automatically associates a data type to the variable, depending on its value. Since the data types
are not set in a strict sense, you can do things like adding a string to an integer without causing an
error.

In PHP 7, type declarations were added. This gives us an option to specify the expected data type
when declaring a function, and by adding the strict declaration, it will throw a "Fatal Error" if the
data type mismatches.

In the following example we try to send both a number and a string to the function without
using strict:

Example
<?php
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is NOT enabled "5 days" is changed to int(5), and it will return 10
?>

To specify strict we need to set declare(strict_types=1);. This must be on the very first line of the
PHP file.

In the following example we try to send both a number and a string to the function, but here we have
added the strict declaration:

Example
<?php declare(strict_types=1); // strict requirement

function addNumbers(int $a, int $b) {


return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is enabled and "5 days" is not an integer, an error will be thrown
?>

PHP Default Argument Value


The following example shows how to use a default parameter. If we call the function setHeight()
without arguments it takes the default value as argument:

Example
<?php declare(strict_types=1); // strict requirement
function setHeight(int $minheight = 50) {
echo "The height is : $minheight <br>";
}

setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>

PHP Functions - Returning values

To let a function return a value, use the return statement:

Example
<?php declare(strict_types=1); // strict requirement
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}

echo "5 + 10 = " . sum(5, 10) . "<br>";


echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>

PHP Return Type Declarations

To declare a type for the function return, add a colon ( : ) and the type right before the opening curly
( { )bracket when declaring the function.

In the following example we specify the return type for the function:

Example
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : float {
return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>
You can specify a different return type, than the argument types, but make sure the return is the
correct type:

Example
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : int {
return (int)($a + $b); //int type
}
echo addNumbers(1.2, 5.2);
?>

6.4. Creating class and objects


OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or functions that perform operations on the
data, while object-oriented programming is about creating objects that contain both data and
functions.

Object-oriented programming has several advantages over procedural programming:

 OOP is faster and easier to execute


 OOP provides a clear structure for the programs
 OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code easier
to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code and shorter
development time.

Example:
<?php
class Fruit {
// Properties
public $name;
public $color;

// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}

$apple = new Fruit();


$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>

6.5. PHP FORM HANDLING:

The PHP superglobals $_GET and $_POST are used to collect form-data.

PHP - A Simple HTML Form

The example below displays a simple HTML form with two input fields and a submit button:

Example
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>

To display the submitted data you could simply echo all the variables. The "welcome.php" looks like
this:

<html>
<body>

Welcome
<?php echo $_POST["name"]; ?><br>
Your email address is:
<?php echo $_POST["email"]; ?>

</body>
</html>

The output could be something like this:

Welcome Harendra Raj Bista


Your email address is [email protected]

Similarly, we can handle form data using GET method:


Example
<html>
<body>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>

and "welcome_get.php" looks like this:

<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>

GET vs. POST

Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2, key3 => value3,
...)). This array holds key/value pairs, where keys are the names of the form controls and values are
the input data from the user.

Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that
they are always accessible, regardless of scope - and you can access them from any function, class or
file without having to do anything special.

$_GET is an array of variables passed to the current script via the URL parameters.

$_POST is an array of variables passed to the current script via the HTTP POST method.

When to use GET?


Information sent from a form with the GET method is visible to everyone (all variable names and
values are displayed in the URL). GET also has limits on the amount of information to send. The
limitation is about 2000 characters. However, because the variables are displayed in the URL, it is
possible to bookmark the page. This can be useful in some cases.

GET may be used for sending non-sensitive data.

Note: GET should NEVER be used for sending passwords or other sensitive information!

When to use POST?


Information sent from a form with the POST method is invisible to others (all names/values are
embedded within the body of the HTTP request) and has no limits on the amount of information to
send.

However, because the variables are not displayed in the URL, it is not possible to bookmark the
page.

Advanced Example:

<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>

PHP Superglobal - $_REQUEST


PHP $_REQUEST

PHP $_REQUEST is a PHP super global variable which is used to collect data after submitting an
HTML form.

The example below shows a form with an input field and a submit button. When a user submits the
data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the
<form> tag. In this example, we point to this file itself for processing form data. If you wish to use
another PHP file to process form data, replace that with the filename of your choice. Then, we can
use the super global variable $_REQUEST to collect the value of the input field:

Example

<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">


Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>

Note:
$_SERVER['PHP_SELF'] Returns the filename of the currently executing script

6.6. PHP Session:


What is a PHP Session?

When you work with an application, you open it, do some changes, and then you close it. This is
much like a Session. The computer knows who you are. It knows when you start the application and
when you end. But on the internet there is one problem: the web server does not know who you are
or what you do, because the HTTP address doesn't maintain state.

Session variables solve this problem by storing user information to be used across multiple pages
(e.g. username, favorite color, etc). By default, session variables last until the user closes the
browser.

So; Session variables hold information about one single user, and are available to all pages in one
application.

Tip: If you need a permanent storage, you may want to store the data in a database.

Start a PHP Session

A session is started with the session_start() function.


Session variables are set with the PHP global variable: $_SESSION.
Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP session
and set some session variables:
Example: demo_session1.php
<?php
// Start the session
session_start(); //this function is the very first thing we have to call
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>

Get PHP Session Variable Values

Next, we create another page called "demo_session2.php". From this page, we will access the
session information we set on the first page ("demo_session1.php").

Notice that session variables are not passed individually to each new page, instead they are retrieved
from the session we open at the beginning of each page (session_start()).

Also notice that all session variable values are stored in the global $_SESSION variable:

Example: demo_session2.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>

Destroy a PHP Session

To remove all global session variables and destroy the session,


use session_unset() and session_destroy():
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>

6.6. PHP Cookies:


What is a Cookie?

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's
computer. Each time the same computer requests a page with a browser, it will send the cookie too.
With PHP, you can both create and retrieve cookie values.

Create Cookies With PHP

A cookie is created with the setcookie() function.

Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
PHP Create/Retrieve a Cookie

The following example creates a cookie named "user" with the value "John Doe". The cookie will
expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire website
(otherwise, select the directory you prefer).

We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also use
the isset() function to find out if the cookie is set:

Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
}

else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>

Note: The setcookie() function must appear BEFORE the <html> tag.
Modify Cookie:
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>

Delete Cookie:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>

6.7 MySQL:
What is MySQL?

 MySQL is a database system used on the web.


 MySQL is a database system that runs on a server.
 MySQL is ideal for both small and large applications.
 MySQL is very fast, reliable, and easy to use.
 MySQL uses standard SQL.
 MySQL compiles on a number of platforms.
 MySQL is free to download and use.
 MySQL is developed, distributed, and supported by Oracle Corporation.
 MySQL is named after co-founder Monty Widenius's daughter: My.

The data in a MySQL database are stored in tables. A table is a collection of related data, and it
consists of columns and rows.

Databases are useful for storing information categorically. A company may have a database with the
following tables:

 Employees
 Products
 Customers
 Orders

PHP Connect to MySQL

Should I Use MySQLi or PDO?

If you need a short answer, it would be "Whatever you like".

Both MySQLi and PDO have their advantages:

PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL
databases.

So, if you have to switch your project to use another database, PDO makes the process easy. You
only have to change the connection string and a few queries. With MySQLi, you will need to rewrite
the entire code - queries included.

Both are object-oriented, but MySQLi also offers a procedural API.

Both support Prepared Statements. Prepared Statements protect from SQL injection, and are very
important for web application security.
We will use MySQLi.

Open Connection to MySQL Server:

<?php
$servername = "localhost";//or 127.0.0.1
$username = "root";
$password = "";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

Closing connection: Object Oriented mysqli close.

$conn->close();

Create a MySQL Database Using MySQLi


<!--Example (MySQLi Object-oriented)-->
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>

MySQL Data Types (Version 8.0)


In MySQL there are three main data types: string, numeric, and date and time.

String data types:


Data type Description
CHAR(size) A FIXED length string (can contain letters, numbers, and
special characters). The size parameter specifies the column
length in characters - can be from 0 to 255. Default is 1
VARCHAR(size) A VARIABLE length string (can contain letters, numbers,
and special characters). The size parameter specifies the
maximum column length in characters - can be from 0 to
65535
BINARY(size) Equal to CHAR(), but stores binary byte strings.
The size parameter specifies the column length in bytes.
Default is 1
VARBINARY(size) Equal to VARCHAR(), but stores binary byte strings.
The size parameter specifies the maximum column length in
bytes.
TINYBLOB For BLOBs (Binary Large OBjects). Max length: 255 bytes
TINYTEXT Holds a string with a maximum length of 255 characters
TEXT(size) Holds a string with a maximum length of 65,535 bytes
BLOB(size) For BLOBs (Binary Large OBjects). Holds up to 65,535
bytes of data
MEDIUMTEXT Holds a string with a maximum length of 16,777,215
characters
MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215
bytes of data
LONGTEXT Holds a string with a maximum length of 4,294,967,295
characters
LONGBLOB For BLOBs (Binary Large OBjects). Holds up to
4,294,967,295 bytes of data
ENUM(val1, val2, val3, ...) A string object that can have only one value, chosen from a
list of possible values. You can list up to 65535 values in an
ENUM list. If a value is inserted that is not in the list, a blank
value will be inserted. The values are sorted in the order you
enter them
SET(val1, val2, val3, ...) A string object that can have 0 or more values, chosen from a
list of possible values. You can list up to 64 values in a SET
list

Numeric data types:


Data type Description
BIT(size) A bit-value type. The number of bits per value is
specified in size. The size parameter can hold a value
from 1 to 64. The default value for size is 1.
TINYINT(size) A very small integer. Signed range is from -128 to 127.
Unsigned range is from 0 to 255. The size parameter
specifies the maximum display width (which is 255)
BOOL Zero is considered as false, nonzero values are
considered as true.
BOOLEAN Equal to BOOL
SMALLINT(size) A small integer. Signed range is from -32768 to 32767.
Unsigned range is from 0 to 65535. The size parameter
specifies the maximum display width (which is 255)
MEDIUMINT(size) A medium integer. Signed range is from -8388608 to
8388607. Unsigned range is from 0 to 16777215.
The size parameter specifies the maximum display width
(which is 255)
INT(size) A medium integer. Signed range is from -2147483648 to
2147483647. Unsigned range is from 0 to 4294967295.
The size parameter specifies the maximum display width
(which is 255)
INTEGER(size) Equal to INT(size)
BIGINT(size) A large integer. Signed range is from -
9223372036854775808 to 9223372036854775807.
Unsigned range is from 0 to 18446744073709551615.
The size parameter specifies the maximum display width
(which is 255)
FLOAT(size, d) A floating point number. The total number of digits is
specified in size. The number of digits after the decimal
point is specified in the d parameter. This syntax is
deprecated in MySQL 8.0.17, and it will be removed in
future MySQL versions
FLOAT(p) A floating point number. MySQL uses the p value to
determine whether to use FLOAT or DOUBLE for the
resulting data type. If p is from 0 to 24, the data type
becomes FLOAT(). If p is from 25 to 53, the data type
becomes DOUBLE()
DOUBLE(size, d) A normal-size floating point number. The total number
of digits is specified in size. The number of digits after
the decimal point is specified in the d parameter
DOUBLE PRECISION(size, d)
DECIMAL(size, d) An exact fixed-point number. The total number of digits
is specified in size. The number of digits after the
decimal point is specified in the d parameter. The
maximum number for size is 65. The maximum number
for d is 30. The default value for size is 10. The default
value for d is 0.
DEC(size, d) Equal to DECIMAL(size,d)

Date and Time data types:


Data type Description
DATE A date. Format: YYYY-MM-DD. The supported range is from '1000-
01-01' to '9999-12-31'
DATETIME(fsp) A date and time combination. Format: YYYY-MM-DD hh:mm:ss.
The supported range is from '1000-01-01 00:00:00' to '9999-12-31
23:59:59'. Adding DEFAULT and ON UPDATE in the column
definition to get automatic initialization and updating to the current
date and time
TIMESTAMP(fsp) A timestamp. TIMESTAMP values are stored as the number of
seconds since the Unix epoch ('1970-01-01 00:00:00' UTC). Format:
YYYY-MM-DD hh:mm:ss. The supported range is from '1970-01-01
00:00:01' UTC to '2038-01-09 03:14:07' UTC. Automatic
initialization and updating to the current date and time can be
specified using DEFAULT CURRENT_TIMESTAMP and ON
UPDATE CURRENT_TIMESTAMP in the column definition
TIME(fsp) A time. Format: hh:mm:ss. The supported range is from '-838:59:59'
to '838:59:59'
YEAR A year in four-digit format. Values allowed in four-digit format: 1901
to 2155, and 0000.
MySQL 8.0 does not support year in two-digit format.

Create MySQL Table using MySQLi:


<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// create tableWhenever(unsigned means we cannot insert negative numbers)


$sql = "CREATE TABLE Student_tbl (
StudentId INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
FirstName VARCHAR(30) NOT NULL,
LastName VARCHAR(30) NOT NULL,
Email VARCHAR(50),
Reg_Date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIM
ESTAMP
)";
//Adding DEFAULT and ON UPDATE in the column definition to get automatic init-
ialization and updating to the current date and time
if ($conn->query($sql) === TRUE) {
echo "Table Student_tbl created successfully";
} else {
echo "Error creating table: " . $conn->error;
}

$conn->close();
Insert Data Into MySQL Using MySQLi
After a database and a table have been created, we can start adding data in them.
Here are some syntax rules to follow:
 The SQL query must be quoted in PHP
 String values inside the SQL query must be quoted
 Numeric values must not be quoted
 The word NULL must not be quoted
The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)

The SQL SELECT Statement

The SELECT statement is used to select data from a database.


The data returned is stored in a result table, called the result-set.

SELECT Syntax
SELECT column1, column2, ...
FROM table_name;

Here, column1, column2, ... are the field names of the table you want to select data from. If you want
to select all the fields available in the table, use the following syntax:

SELECT * FROM table_name;

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT StudentId, FirstName, LastName FROM Student_tbl";


$result = $conn->query($sql);

// fetch_assoc() function fetches a result row as an associative array.


if ($result->num_rows > 0) {//if row data
// output data of each row
while ($row = $result->fetch_assoc()) { //just like result.next()
echo "id: " . $row["StudentId"] . " -
Name: " . $row["FirstName"] . " " . $row["LastName"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();

Code lines to explain from the example above:

First, we set up an SQL query that selects the StudentId, FirstName and LastName columns from the
Student_tbl table. The next line of code runs the query and puts the resulting data into a variable
called $result.

Then, the function num_rows() checks if there are more than zero rows returned.

If there are more than zero rows returned, the function fetch_assoc() puts all the results into an
associative array that we can loop through. The while() loop loops through the result set and outputs
the data from the StudentId, FirstName and LastName columns.

Select and Filter Data From a MySQL Database

The WHERE clause is used to filter records.

The WHERE clause is used to extract only those records that fulfill a specified condition.

Syntax:

SELECT column_name(s) FROM table_name WHERE column_name operator value

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT StudentId, FirstName, LastName FROM Student_tbl WHERE lastname='Hari'";


$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
echo "id: " . $row["StudentId"] . " -
Name: " . $row["FirstName"] . " " . $row["LastName"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();

Select and Order Data From a MySQL Database

The ORDER BY clause is used to sort the result-set in ascending or descending order.

The ORDER BY clause sorts the records in ascending order by default. To sort the records in
descending order, use the DESC keyword.

SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC

Example:
$sql = "SELECT * FROM Student_tbl ORDER BY LastName";
$result = $conn->query($sql);

Delete Data From a MySQL Table Using MySQLi

The DELETE statement is used to delete records from a table:

DELETE FROM table_name


WHERE some_column = some_value

Example:
$sql = "DELETE FROM Student_tbl WHERE id=3";

if ($conn->query($sql) === TRUE) {


echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}

Update Data In a MySQL Table Using MySQLi

The UPDATE statement is used to update existing records in a table:

UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

Example:
$sql = "UPDATE Student_tbl SET LastName='Pokhrel', FirstName='Hari' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

Insert Multiple Data in Table:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO Student_tbl (FirstName, LastName, Email)


VALUES ('Shyam', 'Shrestha', '[email protected]');";
$sql .= "INSERT INTO Student_tbl (FirstName, LastName, Email)
VALUES ('Hari', 'Wagle', '[email protected]');";
$sql .= "INSERT INTO Student_tbl (FirstName, LastName, Email)
VALUES ('Saphina', 'Benjakar', '[email protected]')";

if ($conn->multi_query($sql) === TRUE) {


echo "Multpile New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

Prepared Statement:[not in course]

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// prepare and bind


//'?' is a parameter marker used for values of row data
$stmt = $conn-
>prepare("INSERT INTO Student_tbl (FirstName, LastName, Email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $FirstName, $LastName, $Email);//s for string data type

// set parameters and execute


$FirstName = "Raja";
$LastName = "Hamal";
$Email = "[email protected]";
$stmt->execute();

$FirstName = "Rani";
$LastName = "Hamal";
$Email = "[email protected]";
$stmt->execute();

$FirstName = "Mantri";
$LastName = "Maharjan";
$Email = "[email protected]";
$stmt->execute();

echo "New records created successfully";

$stmt->close();
$conn->close();
?>

6.8 Introduction to Codeignitor:


CodeIgniter is an application development framework, which can be used to develop websites, using
PHP. It is an Open Source framework. It has a very rich set of functionality, which will increase the
speed of website development work.

If you know PHP well, then CodeIgniter will make your task easier. It has a very rich set of libraries
and helpers. By using CodeIgniter, you will save a lot of time, if you are developing a website from
scratch. Not only that, a website built in CodeIgniter is secure too, as it has the ability to prevent
various attacks that take place through websites.

CodeIgniter Features
Some of the important features of CodeIgniter are listed below −

1. Model-View-Controller Based System


2. Extremely Light Weight

3. Full Featured database classes with support for several platforms.

4. Query Builder Database Support

5. Form and Data Validation

6. Security and XSS Filtering

7. Session Management

8. Email Sending Class. Supports Attachments, HTML/Text email, multiple protocols (sendmail,
SMTP, and Mail) and more.

9. Image Manipulation Library (cropping, resizing, rotating, etc.). Supports GD, ImageMagick, and
NetPBM

10. File Uploading Class

11. FTP Class

12. Localization

13. Pagination

14. Data Encryption, so on.

Introduction to Laravel

Laravel is an open-source PHP framework, which is robust and easy to understand. It follows a
model-view-controller design pattern. Laravel reuses the existing components of different
frameworks which helps in creating a web application. The web application thus designed is more
structured and pragmatic.

Laravel offers a rich set of functionalities which incorporates the basic features of PHP frameworks
like CodeIgniter, Yii and other programming languages like Ruby on Rails. Laravel has a very rich
set of features which will boost the speed of web development.

If you are familiar with Core PHP and Advanced PHP, Laravel will make your task easier. It saves a
lot time if you are planning to develop a website from scratch. Moreover, a website built in Laravel
is secure and prevents several web attacks.
Advantages of Laravel

Laravel offers you the following advantages, when you are designing a web application based on it
−The web application becomes more scalable, owing to the Laravel framework.Considerable time is
saved in designing the web application, since Laravel reuses the components from other framework
in developing web application.

It includes namespaces and interfaces, thus helps to organize and manage resources.

Composer

Composer is a tool which includes all the dependencies and libraries.

Artisan

Command line interface used in Laravel is called Artisan. It includes a set of commands which
assists in building a web application. These commands are incorporated from Symphony framework,
resulting in add-on features in Laravel 5.1 (latest version of Laravel).

Features of Laravel

Laravel offers the following key features which makes it an ideal choice for designing web
applications −

Modularity

Laravel provides 20 built in libraries and modules which help in enhancement of the application.

Testability

Laravel includes features and helpers which help in testing through various test cases. This feature
helps in maintaining the code as per the requirements.

Routing

Laravel provides a flexible approach to the user to define routes in the web application. Routing
helps to scale the application in a better way and increases its performance.

Configuration Management

A web application designed in Laravel will be running on different environments, which means that
there will be a constant change in its configuration. Laravel provides a consistent approach to handle
the configuration in an efficient way.

Query Builder and ORM

Laravel incorporates a query builder which helps in querying databases using various simple chain
methods. It provides ORM (Object Relational Mapper) and ActiveRecord implementation called
Eloquent.
Schema Builder

Schema Builder maintains the database definitions and schema in PHP code. It also maintains a track
of changes with respect to database migrations.

Template Engine

Laravel uses the Blade Template engine, a lightweight template language used to design hierarchical
blocks and layouts with predefined blocks that include dynamic content.

E-mail

Laravel includes a mail class which helps in sending mail with rich content and attachments from the
web application.

Authentication

User authentication is a common feature in web applications. Laravel eases designing authentication
as it includes features such as register, forgot password and send password reminders.

Redis

Laravel uses Redis to connect to an existing session and general-purpose cache. Redis interacts with
session directly.

Queues

Laravel includes queue services like emailing large number of users or a specified Cron job. These
queues help in completing tasks in an easier manner without waiting for the previous task to be
completed.

Event and Command Bus

Laravel 5.1 includes Command Bus which helps in executing commands and dispatch events in a
simple way. The commands in Laravel act as per the application‘s lifecycle.

Introduction to Wordpress:

WordPress can be defined as an open-source CMS that has been licensed under GPLv2. It means
anyone has the right to use as well as modify the WordPress software for free. It can be considered
as a tool that makes the life of content publishers easy to manage an essential portion of the website
like website contents, and multimedia files in web pages without having prior knowledge of web
programming. The ultimate result is that WordPress helps develop and build a website handy for
anyone, even without the skill set of a developer.

PHP code can be used in Wordpress created applications for modifications.

You might also like