Web Technology Complete Notes
Web Technology Complete Notes
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
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
3. Learning PHP, MySQL & JavaScript: with jQuery, CSS & HTML5, Robin Nixon, O’Reilly
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)
1. Exchange emails.
2. Send/receive documents, sound, animation and graphics or picture files all over the world.
3. Video Calls
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.
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.
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.
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.
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.
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.
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
3-Tier Architecture
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.
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:
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 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.
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>.
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>
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.
<!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>
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> Tag
It is empty tag.
<address> 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:
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 <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.
<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 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>
<!--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:
HTML 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>
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>
<!--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>
<dt>Milk</dt>
</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.
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.
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>
</html>
<!--navigation_frame.htm-->
<html>
<frameset cols="15%,*">
<frame src="html_contents.htm">
</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:
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>
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.
Username:
</form>
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>
.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 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:
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>
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 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
Example:
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)
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.
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
/*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>
<!--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>
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.
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.
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
CSS Padding:
• The CSS Padding properties define the space between the element border and the element
content.
• 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 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:
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:
Example:
<!DOCTYPE html>
<html>
<head>
<style>
.div1 {
background: red;
float: left;
}
.div2 {
background: yellow;
float:right;
}
.div3 {
background: green;
float:none;
}
</style>
</head>
<body>
CSS3 Borders
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>
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>
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;
} }
It uses the @media rule to include a block of CSS properties only if a certain condition is true.
• Condition is:
– If the browser window is 600px or smaller, the background color will be lightblue:
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:
Implementations:
<!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
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.
<html>
<head><title>JavaScript Strucutre</title></head>
<body>
<h2>Javascript Demonstration</h2>
</body>
</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.
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.
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).
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.
let atmPin=1111;
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>
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.
Two types:
● Decision-making statements
● Loops
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>
● 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:
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?
An array can hold many values under a single name, and you can access the values by referring to an
index number.
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};
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 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;
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");
<!--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?");
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);
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);
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;
}
// 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:
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?
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.
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:
Object
var person = {firstName:"John", lastName:"Doe", age:46};
Accessed using person.firstName, person.lastName and so on.
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;
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>
<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>
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.
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)
<!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>
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>");
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
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;
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>
<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);
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
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()
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
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>
<!DOCTYPE html>
<html>
<body>
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
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
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;
}
document.write(myBike.company+"<br/>"+myBike.model+"<br/>"+myBike.year);
</script>
</body>
</html>
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;
}
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.
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.
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
<script>
function changeText(tag) {
tag.innerHTML = "Changed Text!";
}
</script>
</body>
</html>
<!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>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
</body>
</html>
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 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 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>
<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>
<!DOCTYPE html>
<html>
<body>
<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.
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>
<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).
If you use throw together with try and catch, you can control program flow and generate custom
error messages.
Example:
<!DOCTYPE html>
<html>
<body>
<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";
}
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;
}
Example
try {
decodeURI("%%%"); // You cannot URI decode percent signs
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
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>
</body>
</html>
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.
<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: $().
Example
When a user clicks on a button, the element with id="test" will be hidden:
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
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
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");
}
});
$("#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);
});
});
<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
What is JSON?
JSON stands for JavaScript Object Notation
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 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 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
JavaScript
DOM
CSS
1. Allows for a clear separation of the presentation style from the content and may be changed
programmatically by JavaScript
XMLHttpRequest
Examples:
Google maps, yahoo maps, Google suggest, Gmail, etc. are some good examples that are using
AJAX for quick execution of their applications.
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.
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:
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
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")
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>
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.
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.
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 < 1000 then</message>
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.
<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).
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>
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.
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>
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.
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend</body>
</note>
of type "#PCDATA"
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>
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: " ". 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.
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
& < and > 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 />
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
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.
d elements
ibutes
<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>
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.
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>
<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>
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>
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>
<product pid="1345"/>
<employee>
<firstname>John</firstname>
<lastname>Smith</lastname>
</employee>
<description>
It happened on <date lang="norwegian">03.03.99</date> ....
</description>
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:
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>
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.
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>
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>
<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":
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.
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>
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:
//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:
/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
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:
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:
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)
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]
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
<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.
What is XSLT?
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.
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 > 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 > 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 > 10">
<td bgcolor="#ff00ff">
<xsl:value-of select="artist"/></td>
</xsl:when>
<xsl:when test="price > 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.
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.
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.
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.
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>
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.
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Conditional 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.
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.
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 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>
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>";
}
?>
<?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.
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?
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] . ".";
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:
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");
?>
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
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);
?>
Example
<?php declare(strict_types=1); // strict requirement
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}
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);
?>
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.
Example:
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
The PHP superglobals $_GET and $_POST are used to collect form-data.
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>
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>
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.
Note: GET should NEVER be used for sending passwords or other sensitive information!
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 $_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>
<?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
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.
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>
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.
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?
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
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 support Prepared Statements. Prepared Statements protect from SQL injection, and are very
important for web application security.
We will use MySQLi.
<?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";
$conn->close();
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_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:
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:
<?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);
}
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.
The WHERE clause is used to extract only those records that fulfill a specified condition.
Syntax:
<?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);
}
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();
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.
Example:
$sql = "SELECT * FROM Student_tbl ORDER BY LastName";
$result = $conn->query($sql);
Example:
$sql = "DELETE FROM Student_tbl WHERE id=3";
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;
}
<?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);
}
$conn->close();
<?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);
}
$FirstName = "Rani";
$LastName = "Hamal";
$Email = "[email protected]";
$stmt->execute();
$FirstName = "Mantri";
$LastName = "Maharjan";
$Email = "[email protected]";
$stmt->execute();
$stmt->close();
$conn->close();
?>
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 −
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
12. Localization
13. Pagination
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
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.
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.
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.
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.