CCS375 Web Technologies Lecture Notes 1
CCS375 Web Technologies Lecture Notes 1
com
CCS375-Web Technologies Unit – 1 V Semester CSE
Server:
The software that distributes the information and the machine where the
information and software reside is called the server.
provides requested service to client
e.g., Web server sends requested Web page
Client:
The software that resides on the remote machine, communicates with the
server, fetches the information, processes it, and then displays it on the
remote machine is called the client.
initiates contact with server (speaks first)
typically requests service from server
Web client is implemented in browser
Web server: Software that delivers Web pages and other documents to
browsers using the HTTP protocol.
Website: A collection of pages on the World Wide Web those are accessible
from the same URL and typically residing on the same server.
CLIENT-SERVER PARADIGM
The Client-Server paradigm is the most prevalent model for distributed
computing protocols. It is the basis of all distributed computing paradigms at a
higher level of abstraction.
It is service-oriented, and employs a request-response protocol.
this, providing that the tiers are logically separated can be hosted
(e.g. development and testing) on the same computer.
Advantages:
Ease in Developing Applications:
User Satisfaction:
Applicable for Homogeneous Environment:
High Performance:
Limitations:
The two tier architecture proved to be a good solution when user population
work is usually small (up to about 100 concurrent users) but it rapidly proved to
have a number of limitations:
Performance: Performance begins to deteriorate as the population
grows.
Security: Each user must have their own individual access to the
database, and be granted whatever rights may be required in order to
run the application.
Capability: Independent of the type of client, much of the data
processing has to be located in database making it totally dependent
upon the capabilities and implementation provided by the database
manufacturer.
Portability: As the two-tier architecture is dependent upon the specific
database implementation, porting an existing application to a different
DBMS becomes a major issue.
1) Three-Tier Architecture
In the three-tier architecture the functional process logic, data access,
computer data storage and user interface are developed and maintained
as independent modules on separate platform.
(i) Presentation Tier: Occupies the top level and displays information related
to service available on a website. This tier communicates with other tiers by
sending results to the browser and other tiers in the network.
(ii) Application Tier: Also called the middle tier, logic tier or business logic,
this tier is pulled from the presentation tier. It controls application functionality
by performing detailed processing.
(iii) Data Tier: Houses database server where information is stored and
retrieved. Data in this tier is kept independent of application servers or business
logic.
Advantages:
Improved Data Integrity
Enhanced Security
Hidden Database Structure
Limitations:
Complexity of Communication: Usually more efforts should be ensured
when creating 3-tier applications as the communication points are
increased (client to middle tier to server) and the performance increased
by tools like Visual Basics, Power Builder etc.
2) N-Tier Architecture
N Tier Architecture often referred as Multitier Architecture. It is
client-server architecture in which presentation, application
processing, and data management functions are physically separated.
it is an expanded form of three-tierarchitecture.
Advantages:
It provides a model by which developers can create flexible and reusable
applications. By segregating an application into tiers, developer acquires
the option of modifying or adding a specific layer, instead of reworking
the application.
Limitations:
Difficult to Implement: Due to componentization of tiers, the
complex structure is difficult to implement or maintain.
IP ADDRESSING:
Each host on a TCP/IP network is assigned a unique 32 bit logical
address and it is called as Internet Protocol Address (IP Address). IP
address is used to identify a particular host on the internet.
5 classes of IP address:
FIREWALLS:
The hardware and software that sits between the internet and the local
network, checking all the data that comes in and out to make sure that it is
legitimate is called a Firewall.
The most basic firewall is a packet filter that inspects each packet coming in
or out of a network and uses a set of rules to determine whether that traffic is
allowed.
PROXY SERVERS:
A proxy server is computer that functions as an intermediary between a web
browser (such as Internet Explorer) and the Internet. Proxy servers help improve web
performance by storing a copy of frequently used webpages. When a browser requests
a webpage stored in the proxy server's collection (its cache), it is provided by the
proxy server, which is faster than going to the web. Proxy servers also help improve
security by filtering out some web content and malicious software.
u1 u2 u3 tec
cse ece it
Uniquely traced with the help of domain name space (http://www.cse.tec.ac.in)
10
11
12
Header Data
The unit of data transfer between two devices using TCP is called as
Segment. The segment consists of 20 to 60 byte header followed by data from
the application program.
2. User Datagram Protocol (UDP):
13
Destination Port Number: 16 bit port number used by the process running
on the destination host.
Length: 16 bit field that defines the total length of the user datagram [header
+ data].
Checksum: This field is used to detect errors over the entire user datagram
[header+data]. This ensures that the fields have not changed from the source to
destination.
Applications:
14
TCP UDP
User Datagram Protocol
Transmission Control
Acronym for or Universal Datagram
Protocol
Protocol
TCP is a connection- UDP is a connectionless
Connection
oriented protocol. protocol.
UDP is suitable for
applications that need
TCP is suited for fast, efficient
applications that transmission, such as
Usage require high reliability, games. UDP's stateless
and transmission time nature is also useful for
is relatively less critical. servers that answer
small queries from huge
numbers of clients.
UDP has no order as all
packets are independent
TCP rearranges data
Ordering of data of each other. If
packets in the order
packets ordering is required, it
specified.
has to be managed by
the application layer.
UDP is faster because
The speed for TCP is
Speed of transfer there is no error-
slower than UDP.
checking for packets.
15
16
3. Internet Protocol(IP):
The Internet Protocol (IP) is the principal communications protocol in the
Internet protocol suite for relaying datagrams across network boundaries.
Its routing function enables internetworking, and essentially establishes
the Internet.
IP is the host-to-host network layer protocol for the internet.
IP is connection less and unreliable protocol. It is connection less in the
sense that no state related to IP datagrams is maintained either on
source or destination side
It is unreliable in the sense that it not guaranteed that an IP data gram
will get delivered to the destination or not.
If an IP datagram encounters some error at the destination or at some
intermediate host (while traveling from source to destination) then the IP
datagram is generally discarded and an ICMP error message is sent back to
the source.
If reliability is important, it must be paired with a reliable protocol such
as TCP.
IP Header Format:
Protocol Version(4 bits) : This is the first field in the protocol header.
This field occupies 4 bits. This signifies the current IP protocol version being
used.
Header Length(4 bits) : This field provides the length of the IP header. The
length of the header is represented in 32 bit words.
17
18
FTP data is sent and received through computer port 21 and under the
TCP protocol.
The transfer is asynchronous, meaning not at the same time and
therefore faster than other protocols.
19
20
Internet WWW
Internet is a massive WWW is a way of accessing
Definition network of networks, a information over the
networking infrastructure medium of the internet
It connects millions of
computers together
globally forming a network
It is an information sharing
in which any computer can
Purpose model that is built on the
communicate with any
top of internet.
other computer as long as
both are connected to
internet
Name of the
ARPANET NSFnet
first version
Network of computers,
Files, folders & documents
Comprises copper wires, fiber-optic
stored in various computers
cables 7 wireless networks
Governed Hyper Text Transfer
Internet Protocol
by Protocol
This is the base, It depends on internet to
Dependency
independent of the WWW work
Created by Tim Berners Lee
Creator No such creator
in 1992.
Nature Hardware Software
22
Start line
23
25
301 - Moved Permanently The resource has permanently moved to a different URI.
404 - Not Found The requested resource does not exist on the server.
408 - Request Timeout The client failed to send a request in the time allowed by
the server.
27
WEB SERVER:
A Web Server is basically a computer that is designed to
accept requests from remote computers and send on the
information requested over the internet. It is also used to host
website / web application.
The primary function of a web server is to store, process and deliver web
pages to clients.
The communication between client and server takes place using the
Hypertext Transfer Protocol (HTTP).
Pages delivered are most frequently HTML documents, which mayinclude
images, style sheets and scripts in addition to text content.
28
Examples:
Apache
o Source: The Apache Software Foundation
o Operating System: Unix, Windows NT
o Current Version: 2.2.6
Internet Information Server
o Source: Microsoft
o Operating System: Windows Server 2003
o Current Version: 6.0
Sun Java System Web Server
o Source: Sun Microsystems
o Operating System: Solaris, Windows Server 2003,
2000, XP, Linux, HP-UX
o Current Version: 7.0
WEB CLIENT:
A Web client is the browser on the PC/Mac that makes the
requests to the remote server. It is an application (e.g.
Internet Explorer, Firefox, Chrome, Safari, and Opera) running on a local
device (desktop, notebook, cell phone) used to interact mainly with Web
servers. A PC/Mac that uses a web (Client) browser is referred to as a Client
Machine.
The primary function of a web client is to serve content.
A user agent, commonly a web browser or web crawler, initiates
communication by making a request for a specific resource using HTTP
and the server responds with the content of that resource or an error
message if unable to do so.
Functions of a Web Browser:
1. Reformat the URL and send a valid HTTP request.
2. When user gives the address of particular web site, the web browser
converts the DNS to corresponding ip address.
3. The web browser establishes a TCP connection with the web server while
processing the user’s request.
4. The web browser sends the HTTP request to the web server.
5. The web browser displays the response page returned by the server in
appropriate format on the client machine.
29
30
31
WEB SITE:
A Web Site is a set of interconnected webpages on WWW that
includes a beginning file called homepage.
Web sites are accessed by using URLs provided by the authority of
the web site.
Web sites are generally located on the same server, and prepared
and maintained as a collection of information by a person, group, or
organization.
Example: http://www.w3schools.com
DIFFERENCE BETWEEN WEB SERVER AND WEB SITE:
WEB APPLICATION:
A web application or web app is any computer program that runs in a
web browser. It is created in a browser-supported programming language
(such as the combination of JavaScript, HTML and CSS) and relies on a
web browser to render the application.
It is usable only with an active Internet connection
It uses HTTP as its primary communications protocol.
Examples: Online ticket booking applications, Online games, google
docs, etc.,
32
Advantages of HTML:
1. It is plain text so is easy to edit.
2. It is also fast to download.
3. Is very easy to pick up\learn .
4. It is now a standard.
5. It is supported by most browsers.
6. Simple to edit only requires a text editor.
7. Can be easily edited with WYSIWYG editors (no coding required) .
8. Can be used to present just about any kind of data.
9. Tags can be used very loosely (i.e. used to be able to omit end tags
etc).
10. It is user friendly.
11. It is open technology.
Disadvantages of HTML:
1. It can create only static and plain pages so if we need dynamic
pages then HTML is not useful.
2. It is static needs to be manually updated or needs some
scripting support to change it in some way.
3. Need to write lot of code for making simple webpage.
4. Security features are not good in HTML.
5. If we need to write long code for making a webpage then it
produces some complexity.
33
<head>
<title> title of the page </title> Head Section
</head>
<body>
Page design goes here Body Section
</body>
<html>
Common Declarations
HTML 4.01:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
XHTML 1.0:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN"
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
34
HTML CONSTRUCTS:
There are two main constructs in HTML:
1. Elements (also called tags)
2. Entities.
1. Elements:
HTML tags are keywords (tag names) surrounded by angle
brackets. HTML element or tag is a signal to the browser that it
should do something other than just throwing text on the screen. Tags
are descriptions that are embedded directly into the informational text
of the document.
Syntax: <tagname>content</tagname>
35
The end tag is written like the start tag, but with a slash before the
tag name
2. Attributes:
HTML elements can have attributes
Attributes provide additional information about an element
Attributes are always specified in the start tag
Attributes come in name/value pairs like: name="value"
Syntax:
<tagname attributename=‖value‖>content</tagname>
Example: <applet width=‖100‖ height=‖100‖>
3. Entities:
Entities are character sequences that reproduce special
characters on the browser screen.
Reserved characters in HTML must be replaced with character entities
(references).
If you use the less than (<) or greater than (>) signs in your text,the
browser might mix them with tags.
Character entities are used to display reserved characters inHTML.
A character entity looks like this:
&entity_name; OR &#entity_number;
36
3. <base> tag:
Type: Standalone tag
Function: Specifies the base URL of the document.
Syntax:
<base href=‖base-url‖> (or) <base target=‖frame_name‖>
Target – specifies the default frame name to which all the linked
documents should be loaded.
Related Tags: None.
4. <link> tag:
Type: Standalone tag
Function: Makes a link between an external source and this html
file.
Syntax: <link href=‖url-of-the-linked-file‖
title=‖title‖ rel=‖forward-relationaship‖ rev=‖reverse-
relationship‖>
Attributes:
Href – denotes the URL of the file to be linked.
Title – gives the link a descriptive title.
38
Attributes:
language – Scripting language used to write the script.
src – Specifies the URL of a file containing the script code, if
the code is not written between <script> and </script> tags.
type – MIME type of the script code.
Example:
<head>
<script src=‖external.js‖ type=‖text/javascript‖></script>
</head>
Example:
<body bgcolor=‖yellow‖ >
<body bgcolor=‖#0000FF‖ >
<body background=‖flower1.jpg‖>
40
FORMATING TAGS:
1. <b> tag:
Type: Container tag
Function: Makes the enclosed text bold.
Syntax: <b> text </b>
Attributes: None
Example:
<b> Welcome </b>
2. <i> tag:
Type: Container tag
Function: Makes the enclosed text italic.
Syntax: <i> text </i>
Attributes: None
Example:
<i> Welcome </i>
3. <u> tag:
Type: Container tag
Function: Makes the enclosed text underlined.
Syntax: <u> text </u>
Attributes: None
Example:
<u> Welcome </u>
4. <big> tag:
Type: Container tag
Function: Renders the text in the font size bigger than the default
font size.
Syntax: <big> text </big>
Attributes: None
Example: <big> Welcome </big>
5. <small> tag:
Type: Container tag
Function: Renders the text in the font size smaller than the
default font size.
Syntax: <small> text </small>
Attributes: None
Example:<small> Welcome </small>
41
7. <sub> tag:
Type: Container tag
Function: contains the text to be subscript to the text that
precedes it.
Syntax: <sub> text </sub>
Attributes: None
Example:
a<sub>1</sub>, a<sub>2</sub>
8. <sup> tag:
Type: Container tag
Function: contains the text to be super script to the text that precedes it.
Syntax: <sup> text </sup>
Attributes: None
Example:
a<sup>1</sup>, a<sup>2</sup>
9. <font> tag:
Type: Container tag
Function: contains the text whose font properties are to be
modified.
Syntax: <font size=‖size‖ color=‖color‖ face=‖font-face-type‖>
text </font>
Example:
<font face=‖Calibri‖ size=‖25pt‖ color=‖green‖> Welcome
</font>
10. <br> tag:
Type: Empty tag
Function: Inserts a line break in the document.
Syntax: <br/>
Example:<font face=‖Calibri‖ size=‖25pt‖color=‖green‖> Welcome
</font> <br/>
42
44
Output:
Heading 1
Heading 2
Heading 3
Example:
<!DOCTYPE html>
<html>
<body>
<h1> Heading 1 </h1>
<h2> Heading 2 </h2>
<h3> Heading 3 </h3>
<h4> Heading 4 </h4>
<h5> Heading 5 </h5>
<h6> Heading 6 </h6>
</body>
</html>
Output:
Heading 1
Heading 2
Heading 3
Heading 4
Heading 5
Heading 6
1. <p> tag:
Type: Container tag
Function: denotes a paragraph.
Syntax: <p align=‖ LEFT | RIGHT | CENTER‖> paragraph text
</p>
Attributes:
Align – LEFT | RIGHT | CENTER. Controls the alignment of
the text in the paragraph.
Example:
<p align=‖center‖ title=‖Greetings‖> Welcome</p>
47
<pre>
Welcome
To
HTML
</pre>
</body>
</html>
Output:
Welcome To HTML
Welcome
To
HTML
18. <span> tag:
Type: Container tag
Function: Generic tag for defining document block. Used for
applying style information.
Syntax:
<span style=‖style-information‖ align=‖LEFT|RIGHT|CENTER‖>
Text
</span>
Example:
<span style=‖font-weight:bold; color:red;>
Welcome
To
HTML
</span>
48
Tables are used for presenting data in tabular form i.e. to organize data into
rows and columns.
The fundamental building blocks of a table are cells, which can
contain either a data element or a heading for a column of data.
Columns and rows will automatically size to contain their data.
Individual table cells can span multiple rows or columns.
Header and footer rows can be supplied.
HTML Table Tags:
Tag Name Meaning Tag Name Meaning
table Represents start of a tbody Defines the table
table body
caption Describes the table tr Represents a table
content row
thead Defines the header th Represents a column
section header
tfoot Defines the footer td Defines data in the
section cell
49
Attribute Meaning
Align Specifies table alignment. An have values: left,
right, and center
Border Specifies the thickness of the table border in
number of pixels
Background Specifies the URL of the background image
Bordercolor Specifies the color of the table border. color
names or hexadecimal color codes are allowed
Bgcolor Specifies the background color of the table. color
names or hexadecimal color codes are allowed
Height Specifies the height of the table in pixels
Width Specifies the width of the table in pixels
Cols Specifies the number of columns to be created in
the table
Cellpadding Specifies the amount of space in number of
pixels between the cell border and its content
Cellspacing Specifies the amount of space in number of
pixels between table cells.
frame Specifies whether a frame around the table
should be created or not
50
Attributes of tr tag:
Attribute Meaning
Align Specifies the horizontal alignment of the content of
all cells in this row. Can have values: left, right and
center. Default value is left.
Bordercolor Specifies the border color of all cells in this row. color
names or hexadecimal color codes are allowed
Bgcolor Specifies the background color of all cells in this row.
color names or hexadecimal color codes are allowed
Height Specifies height, in pixels, of all cells in this row
Width Specifies width, in pixels, of all cells in this row
valign Specifies the vertical alignment of the content of all
cells in this row. Can have values: top, bottom and
middle. Default value is middle.
51
3. <td> Element:
Attribute Meaning
Align Specifies the horizontal alignment of the content of
all cells in this row. Can have values: left, right and
center. Default value is left.
Bordercolor Specifies the border color of all cells in this row. color
names or hexadecimal color codes are allowed
Bgcolor Specifies the background color of all cells in this row.
color names or hexadecimal color codes are allowed
Height Specifies height, in pixels, of all cells in this row
Width Specifies width, in pixels, of all cells in this row
valign Specifies the vertical alignment of the content of all
cells in this row. Can have values: top, bottom and
middle. Default value is middle.
Colspan Specifies the number of columns this cell must span
rowspan Specifies the number of rows this cell must span
52
Example:
<!DOCTYPE html>
<html>
<head>
<title>Simple Table Demo</title>
</head>
<body>
<table border="1" width="20%">
<caption><strong>Price of Fruits</strong></caption>
<thead>
<tr>
<th>Fruit</th>
<th>Price</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Total</th>
<th>$3.75</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Orange</td>
<td>$0.50</td>
</tr>
<tr>
<td>Banana</td>
<td>$1.00</td>
</tr>
<tr>
<td>pineapple</td>
<td>$2.00</td>
</tr>
<tr>
<td>Apple</td>
53
<td>$0.25</td>
</tr>
</tbody>
</table>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Simple Table Demo</title>
</head>
<body>
<table border="1" width="20%">
<caption><strong>Price of Fruits</strong></caption>
<thead>
<tr>
<th>Fruit</th>
<th>Price</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Total</th>
<th>$3.75</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Orange</td>
<td>$0.50</td>
</tr>
<tr>
<td>Banana</td>
<td>$1.00</td>
</tr>
<tr>
<td>pineapple</td>
<td>$2.00</td>
</tr>
<tr>
<td>Apple</td>
54
Year Subjects
Name
Branch TOC IP
Rowspan Colspan
<td rowspan=‖2‖>Name</td>
<td colspan=‖2‖>Subjects</td>
<td>Year</td><td>Branch</td>
<td>TOC</td><td>IP</td>
Example:
<html>
<head>
<title>Complex Table</title>
</head>
<body>
<table border="1" bgcolor="#FF9900">
<caption> Comparison of districts in Tamil nadu</caption>
<thead>
<tr>
<th rowspan="2"><img src="tamil-nadu-map.jpg" width="150"
height="150"></th>
<th colspan="3"><h1> District comparison in Tamil
nadu</h1></th>
</tr>
<tr>
<th>District</th>
<th>Population</th>
55
<th>Growth</th>
</tr>
</thead>
<tbody align="center">
<tr>
<th>1</th>
<td>Chennai</td>
<td>464673</td>
<td>6.98 %</td>
</tr>
<tr>
<th>2</th>
<td>Coimbatore</td>
<td>3458045</td>
<td>18.56 %</td>
</tr>
<tr>
<th>3</th>
<td>Madurai</td>
<td>3038252</td>
<td>17.84 %</td>
</tr>
</tbody>
</table>
</body>
</html>
56
57
</cetner>
</body>
</html>
58
INTERNAL LINKING:
Internal linking is a mechanism that enables the user to jump
between locations in the same document.
Internal linking is useful for long documents that contain many
sections.
59
60
3
4
5
6
7
8
9
10
</pre>
</font>
<center><a href="#top"> Go Up</a></center>
<hr color="orange">
<h1><a name="upper"><font color="yellow">UPPERCASE
ALPHABETS</font></a>
</h1>
<font size=5pt>
<pre>
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
61
U
V
W
X
Y
Z
</pre>
</font>
<center><a href="#top"> Go Up</a></center>
<hr color="orange">
<h1><a name="lower">
<font color="yellow">LOWERCASE ALPHABETS</font></a></h1>
<font size=5pt>
<pre>
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
62
x
y
z
</pre>
</font>
<center><a href="#top"> Go Up</a></center>
<hr color="orange">
</body>
</html>
Bullet Options:
Bullet Options Meaning Result
<ul> Default bullet shape is disc One
Two
<ul type=‖disc‖> Disc shaped bullets are used One
Two
<ul type=‖circle‖> Circle shaped bullets are used o One
63
o Two
<ul Square shaped bullets are used One
type=‖square‖> Two
2. Ordered Lists:
Numbering Options:
Numbering Numbering
Meaning Result Meaning Result
options options
Use
Use default
1. One <ol lowercase a. One
<ol> number
2. Two type=‖a‖> letters for b. Two
type
numbering
Use
Use default <ol lowercase
<ol 1. One d. One
number type=‖a‖ letters
type=‖1‖> 2. Two e. Two
type start=‖4‖> stating
from d
Use
Use small
<ol uppercase A. One <ol i. One
roman
type=‖A‖> letter for B. Two type=‖i‖> ii. Two
numbers
numbering
<ol Use default 3. One <ol type=‖i‖ Use small ii. One
type=‖3‖> number 4. Two start=‖2‖> roman iii. Two
64
starting numbers
form 3 starting
from ii
Use
Use
<ol uppercase
D. One <ol capital I. One
type=‖A‖ letters
E. Two type=‖I‖> roman II. Two
start=‖4‖> starting
numbers
from D
3. Definition List:
A definition list is the one where list items consist of two parts:
o a term
o its description
Definition List is created using <dl> tag.
The term part and the definition part of each item are created
using <dt> (definition term) and <dd> (definition description)
tags respectively.
Example:
<dl>
<dt> dl tag </dt>
<dd> it is the outermost tag of definition list</dd>
<dt> dt tag </dt>
<dd> Contains the item to be described</dd>
<dt> dd tag </dt>
<dd> Contains description of the item</dd>
<dd> Each term may have multiple descriptions</dd>
</dl>
dl tag
it is the outermost tag of definition
list
dt tag
Contains the item to be described
dd tag
Contains description of the item
Each term may have multiple
descriptions
65
NESTED LISTS:
Lists may be nested to represent hierarchical relationships.
A web browser indents each nested list to indicate a hierarchical
relationship.
Any of the three types of lists may be nested in another.
Arbitrary levels of nesting is possible
<!DOCTYPE html>
<html>
<head>
<title> List Example</title>
</head>
<body bgcolor="violet">
<center>
<h1> ABC ENGINEERING COLLEGE</h1>
</center>
<hr color="blue">
<ul>
<li> U.G Courses
<ol>
<li> B.E - CSE </li> Inner List
<li> B.E - ECE </li>
</ol>
</li>
<li> P.G Courses
<ol>
Outer List
<li> M.E - CSE </li>
<li> M.E - SE </li>
<li> MBA </li> Inner List
<li> MCA </li>
</ol>
</li>
</ul>
<hr color="red">
66
<ul type="square">
<li>
<dl>
<dt> CSE </dt>
<dd> Computer Science and Engineering</dd>
</dl>
</li>
<li>
<dl>
<dt> ECE</dt>
<dd> Electronics and Communication
Engineering</dd>
</dl>
</li>
<li>
<dl>
<dt> SE </dt>
<dd> Software Engineering</dd>
</dl>
</li>
</ul>
</body>
</html>
Output:
67
HTML Forms
<form> ELEMENT:
The <form> element is used to create a form.
Syntax:
<form name=‖form_name‖ accept=‖MIME _type‖
action=‖URL_of_the_Script‖
Method=‖GET|POST‖ target=‖frame_name‖ >
- Form elements --
</form>
Attributes:
Attribute Description
accept- Specifies the charset used in the submitted form (default:
charset the page charset).
Specifies an address (url) where to submit the form
action
(default: the submitting page).
Specifies if the browser should autocomplete the form
autocomplete
(default: on).
Specifies the encoding of the submitted data (default: is
enctype
url-encoded).
68
Example:
<form name=‖form1‖ method=‖get‖
action="action_page.php">
----- form elements ----
</form>
<input> ELEMENT:
The <input> element is the most important form element.
The <input> element has many variations, depending on the type
attribute.
<html>
<body>
<form action="">
User name:<br>
<input type="text" name="userid">
<br>
User password:<br>
<input type="password" name="psw">
</form>
<p>The characters in a password field are masked (shown as
asterisks or circles).</p>
</body>
</html>
TEXTAREA ELEMENT:
This control allows the user to enter multiple lines of data.
It is generated on the web page using <textarea> and </textarea>
tag pair.
Size of the textarea is specified usingthe two attributes rows and
cols.
72
SELECT ELEMENT:
A menu is defined using ―select‖ element. It defines the drop-down
list.
It is used to produce scrollable option menus.
Syntax:
<select name=”Name” [size=”size”] [MULTIPLE] >
<option value=”value” [selected] > Option1
</option>
<option value=”value” [selected] > Option2
</option>
</select>
Option element is used to define the options to select.
[selected] attribute is used to specify which option should be
selected by default (predefined option).
Example:
<form action="action_page.php">
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<br><br>
<input type="submit">
</form>
<label> Gender:
<input type="radio" name="gender" />Male
<input type="radio" name="gender" />Female </label><br />
<label> D.O.B: <input type="date" name="bday" /> </label>
<br />
<label> Qualification:
<select>
<option value="be">B.E</option>
<option value="ba">B.A</option>
<option value="bcom">B.COM</option>
<option value="bba">B.B.A</option>
</select></label>
<br />
<label> Hobbies:
<input type="checkbox" name="c1" />Playing
<input type="checkbox" name="c2" />Singing
<input type="checkbox" name="c3" />Dancing </label> <br />
80
Downloaded from EnggTree.com
EnggTree.com
CCS375-Web echnologies Unit – 1 V Semester CSE
81
Downloaded from EnggTree.com
EnggTree.com
CCS375-Web echnologies Unit – 1 V Semester CSE
1. <datalist> Element:
The <datalist> element specifies a list of pre-defined options for an
<input> element.
Users will see a drop-down list of pre-defined options as they input
data.
The list attribute of the <input> element, must refer to the id
attribute of the <datalist> element.
Example
An <input> element with pre-defined values in a <datalist>:
<form action="action_page.php">
<input list="browsers">
<datalist id="browsers">
<option value="Internet
Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</form>
2. <keygen> Element:
The purpose of the <keygen> element is to provide a secure way to
authenticate users.
The <keygen> element specifies a key-pair generator field in a form.
When the form is submitted, two keys are generated, one private
and one public.
The private key is stored locally, and the public key is sent to the
server.
The public key could be used to generate a client certificate to
authenticate the user in the future.
3. <output> Element:
The <output> element represents the result of a calculation (like
one performed by a script).
Example:
<form action="action_page.asp"
oninput="x.value=parseInt(a.value)+parseInt(b.value)">
0
<input type="range" id="a" name="a" value="50">
100 +
<input type="number" id="b" name="b" value="50">
=
<output name="x" for="a b"></output>
<br><br>
<input type="submit">
</form>
Input Restrictions:
Here is a list of some common input restrictions (some are new in
HTML5):
Tag Description
<details> Defines additional details that the user can view or hide
Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>...</title>
</head>
<body>
<header role="banner">
<h1>HTML5 Document Structure Example</h1>
<p>This page should be tried in safari, chrome or Mozila.</p>
</header>
<nav>
<ul>
<li><a href="http://www.tutorialspoint.com/html">HTML
Tutorial</a></li>
<li><a href="http://www.tutorialspoint.com/css">CSS
Tutorial</a></li>
<li><a
href="http://www.tutorialspoint.com/javascript">JavaScript
Tutorial</a></li>
</ul>
</nav>
<article>
<section>
<p>Once article can have multiple sections</p>
</section>
</article>
<footer>
<p>Created by <a href="http://tutorialspoint.com/">Tutorials
Point</a></p>
</footer>
</body>
</html>
The DataTransfer object holds data about the drag and drop
operation. This data can be retrieved and set in terms of various
attributes associated with DataTransfer object as explained below –
<!DOCTYPE HTML>
<html>
<head>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</body>
</html>
<audio> element:
The HTML5 <audio> element specifies a standard way to embed audio in
a web page. To play an audio file in HTML, use the <audio> element:
<!DOCTYPE html>
<html>
<body>
<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</body>
</html>
<video> element:
The HTML5 <video> element specifies a standard way to embed a video in
a web page. To show a video in HTML, use the <video> element:
<!DOCTYPE html>
<html>
<body>
<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
</body>
</html>
The controls attribute adds video controls, like play, pause, and
volume.
It is a good idea to always include width and height attributes.
If height and width are not set, the browser does not know the size
of the video. The effect will be that the page will change (or flicker)
while the video loads.
Text between the <video> and </video> tags will only display in
browsers that do not support the <video> element.
Multiple <source> elements can link to different video files. The
browser will use the first recognized format.
Definition:
Cascading Style Sheet (CSS) is a W3C technology that allows document
authors to specify the presentation of elements on a web page (e.g fonts, spacing,
colors) separately from the structure of the document (section headers, body, links).
This separation of structure from presentation simplifies maintaining and modifying
a web page.
1. CSS allows separation between the information contained in the document and its
presentation. Hence any change in the presentation can be made without disturbing
the information of the document.
2. Style Sheets allow users to decide the style of presentation. This presentation style
can be defined in a separate file. Thus the presentation can be made persistent.
3. CSS allows the developer to give the consistent appearance to all the elements of
the web page.
4. CSS allows us to improve the consistent look and feel of a web site.
5. CSS provides precise control over font size, color, background color and so on.
</style>
TYPES OF SELECTOR STRING:
1. Type Selector:
It is the simplest form of selector string which consists of the name of a single element.
A rule can also apply to multiple elements types separating the elements by using comma (,)
Example:
h1, p {background-color:purple}
2. Universal Selector:
It is denoted by an asterisk (*).
A rule denoted by universal selector can be applied for every possible element in the
document.
Example:
* {background-color:purple; font-weight:bold}
3. Id Selector:
A selector preceded by a number sign (#) is called an ID selector.
It represents an id value rather than an element type name.
A rule defined by the ID selector can be applied to the element that matches with the id
attribute value with the ID selector string.
Example:
<style type=”text/css”>
#myid {background-color:green}
</style>
4. Class Selector:
A selector preceded by a period or dot (.) is called an Class selector.
It represents a generic value rather than an element type name.
A rule defined by the class selector can be applied to the element that matches with the class
attribute value with the Class selector string.
Example:
<style type=”text/css”>
.myclass {background-color:red}
</style>
<p class=”myclass”>
This is an class selector
</p>
Note: Class selectors can also be prefixed by an element name which restricts the selector
toelements of the specified type.
5. Pseudo classes:
Using pseudo-classes we can specify special effects on the selectors.
There are some pseudo classes which are more commonly used and those are:
Focus
Hover
hyperlink
General form of pseudo class and pseudo element:
Selector:pseudo-class { declaration
This rule will first read the rules form the specified file “filename.css” before continuing
with the other rule in the style sheet.
@import rule must appear at the beginning of the style sheet before any ruleset statements
and it must end with semicolon (;).
Links.css
a:hover {font-size:200%}
a:active {color:yellow}
a:visited {color:green}
mystyle.css
@import url("links.css");
li { font-size: 14pt; line-height: 25pt }
* { font-family: verdana }
.unorder { background-color:yellow }
#order { background-color:violet }
dl dd {color:blue}
lists.html
<!DOCTYPE html>
<html>
<head>
<title> List Example</title>
</head>
<link href="mystyle.css" rel="stylesheet" type="text/css">
<body >
<center>
<h1 color="green"> ABC ENGINEERING COLLEGE</h1>
</center>
<hr color="blue">
<ul id="order">
<li> U.G Courses
<ol class="unorder">
<li> B.E - CSE </li>
<li> B.E - ECE </li>
</ol>
</li>
<li> P.G Courses
<ol class="unorder">
<li> M.E - CSE </li>
<li> M.E - SE </li>
<li> MBA </li>
<li> MCA </li>
</ol>
</li>
</ul>
<hr color="red">
<ul type="square">
<li>
<dl>
<dt> <a href="">CSE </a></dt>
<dl>
</dl>
</li>
</dl>
<li> </li>
<dl> </ul>
</body>
</html>
</dl>
</li>
<li> <dd> Software Engineering</dd>
<head>
</head>
Example:
Style1.css
.heading
{
font-family: Arial, Helvetica, sans-serif;
background-color:violet;
color:blue;
}
Style_types.html
<!DOCTYPE html>
<html>
<head>
<title>Types of Style Sheets</title>
<style type="text/css">
h1 { font-weight:bold; font-size:12px; color:red }
</style>
<link href="style1.css" type="text/css" rel="stylesheet">
</head>
<body bgcolor="pink">
<center>
<h2>TYPES OF STYLE SHEETS</h2>
<hr>
<p style="background-color:yellow;text-decoration:underline">
This is Inline Style Sheet
</p>
<hr>
<h1> This is Embedded / Internal Style Sheet</h1>
<hr>
<h1 class="heading">This is External Style Sheet</h1>
<hr>
</center>
</body>
</html>
RULE CASCADING:
Consider the following declarations:
* { font-weight: bold } – this rule applies to every element of te HTML document.
#p1, #p3 { background-color:aqua } - both the rules are applied to to an element with id
attribute value p3 and p1.
If multiple rules apply to an element and these rules provide declarations for different properties,
then all of the declarations are applied to the element.
What will happen if multiple declarations that all apply to a single property of a single
element are available?
In order to choose between multiple declarations, the browser applies Rule Cascading. It
is a multi-stage sorting process that selects a single declaration that will supply the property
value.
Mypage.html
<html>
<head>
<style type=”text/css”>
P {color:red }
</style>
<link rel=”stylesheet” type=”text/css” href=”style1.css”>
<style type=”text/css”>
P {color: yellow}
</style>
</head>
In the above example, we find multiple declarations for the same property that all apply to the
same element.
p {color:red }
p {color:blue }
p {color:green }
p {color: yellow} This declaration is selected and the text will be
displayed in yellow color.
STYLE INHERITANCE:
Rule Cascading is based on the structure of the style sheets.
Inheritance is based on the tree structure of the document.
If a value for a style option has not been specified for an element, the element will inherit
the style property form its parent.
If the parent element does not specify the style rule, it inherits from the grand parent and
so on up to the top-level element (either <html> tag or the element with style property).
Inherited style can be overridden by declaring specific style to the child.
Example:
CSS background properties are used to define the background effects of an element.
Example:
<!DOCTYPE html>
<html>
<head>
<title>CSS Backgound</title>
<style type="text/css">
p{
background-color:#99FF99;
background-attachment:fixed;
}
</style>
</head>
<body>
<center> <h1> CSS Backgorund Property</h1>
<p> This paragraph contains a beatiful background image. </p>
<div>ABCD EFG.... HIJK LMNOP... QRSTUVW.....UVW XYZ.</div>
</center>
</body>
</html>
ridge: Defines a 3D ridged border. The effect depends on the border-color value
inset: Defines a 3D inset border. The effect depends on the border-color value
outset: Defines a 3D outset border. The effect depends on the border-color value
Border Width: The border-width property is used to set the width of the border.
The width is set in pixels, or by using one of the three pre-defined values: thin, medium, or thick.
border-style: dotted;
o all four borders are dotted
Example:
p{
border: 5px solid red;
}
<!DOCTYPE html>
<html>
<head>
<style>
p.normal {
border: 2px solid red;
}
p.round1 {
border: 2px solid red;
border-radius: 5px;
}
p.round2 {
border: 2px solid red;
border-radius: 8px;
}
p.round3 {
border: 2px solid red;
border-radius: 12px;
}
</style>
</head>
<body>
Tip: The border-image property is actually a shorthand property for the following
properties:
o border-image-source,
o border-image-slice,
o border-image-width,
border-image-outset Specifies the amount by which the border image area extends
beyond the border box
Example:
<!DOCTYPE html>
<html>
<head>
<style>
#borderimg1 {
border: 10px solid transparent;
padding: 15px;
border-image: url(grid.png) 20% repeat;
background-color:yellow
}
#borderimg2 {
border: 50px solid transparent;
padding: 15px;
border-image: url(rose.jpg) 20% repeat;
color:blue;
font-size:25px
}
#borderimg3 {
</body>
</html>
Colors are specified using predefined color names, or RGB, HEX, HSL, RGBA, HSLA values.
2) HEX Colors
A hexadecimal color is specified with: #RRGGBB, where the RR (red), GG (green) and
BB (blue) hexadecimal integers specify the components of the color.
HEX Value
In CSS, a color can be specified using a hexadecimal value in the form:
#rrggbb
Where rr (red), gg (green) and bb (blue) are hexadecimal values between 00 and ff
(same as decimal 0-255).
For example, #ff0000 is displayed as red, because red is set to its highest value (ff) and
the others are set to the lowest value (00).
3) HSL Colors
HSL stands for hue, saturation, and lightness.
HSL Value
In CSS, a color can be specified using hue, saturation, and lightness (HSL) in the form:
hsl(hue, saturation, lightness)
Hue is a degree on the color wheel from 0 to 360. 0 is red, 120 is green, and 240 is blue.
Saturation is a percentage value, 0% means a shade of gray, and 100% is the full color.
Lightness is also a percentage, 0% is black, 50% is neither light or dark, 100% is white
Saturation
Saturation can be described as the intensity of a color.
100% is pure color, no shades of gray
50% is 50% gray, but you can still see the color.
0% is completely gray, you can no longer see the color.
With CSS you can add shadow to text and to elements with the help of the following properties:
1. text-shadow
2. box-shadow
1. Text Shadow
The CSS text-shadow property applies shadow to text.
In its simplest use, you only specify the horizontal shadow (2px) and the
vertical shadow (2px).
Multiple Shadows
To add more than one shadow to the text, you can add a comma-separated list of
shadows.
The following example shows a red and blue neon glow shadow:
2. box-shadow
The CSS box-shadow property applies shadow to elements.
In its simplest use, you only specify the horizontal shadow and the vertical
shadow.
Example:
<!DOCTYPE html>
<html>
<head>
<title> CSS Text Properties</title>
<style type="text/css">
p.test1 {
color:green;
text-align:center;
text-decoration:underline;
text-indent::10pt;
text-shadow:red;
text-transform:capitalize;
direction:rtl;
letter-spacing:5px;
}
</style>
</head>
<body>
<center><h1>CSS Text Properties</h1></center>
<p class="test1">abcd efgh ijkl mnop qrst uvw xyz</p>
</body>
</html>
Text Overflow:
The CSS3 text-overflow property specifies how overflowed content that is not displayed
should be signaled to the user.
Word Wrapping:
The CSS3 word-wrap property allows long words to be able to be broken and wrap onto
the next line. If a word is too long to fit within an area, it expands outside.
Word Breaking:
The CSS3 word-break property specifies line breaking rules.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
p.test1 {
width: 140px;
border: 1px solid #ff00ff;
word-break: keep-all;
p.test2 {
width: 140px;
border: 1px solid #00ff00;
word-break: break-all;
width: 140px;
border: 1px solid #f0f0f0;
word-wrap:break-word;
}
</style>
</head>
<body>
</body>
</html>
generic family - a group of font families with a similar look (like "Serif" or
"Monospace")
font family - a specific font family (like "Times New Roman" or "Arial")
Example:
<html>
p{
font-size:50px;
font-variant:small-caps;
font-family:Arial;
font-weight:bold;
font-style:italic;
color:green;
}
In the CSS3 @font-face rule you must first define a name for the font (e.g. myFirstFont),
and then point to the font file.
To use the font for an HTML element, refer to the name of the font (myFirstFont)
through the font-family property:
Example:
@font-face {
font-family: myFirstFont;
src: url(sansation_light.woff);
}
div {
font-family: myFirstFont;
}
<div>
This is an example for web fonts
</div>
CSS3 supports transform property. This transform property facilitates you to translate, rotate,
scale, and skews elements.
Transformation is an effect that is used to change shape, size and position.
There are two type of transformation i.e. 2D and 3D transformation supported in CSS3.
transform-origin Allows you to change the position on transformed elements. It allows you
to specify the location origin of the transform. By default, the origin is in
the center of the element.
For example, if you are using the transform: rotate property but want it to
div:hover {
transform: rotate(720deg);
}
CSS 2D Transforms
The CSS 2D transforms are used to re-change the structure of the element
as translate, rotate, scale and skew etc.
Function Description
translate(x,y) Defines a 2D translation, moving the element along the X- and the Y-
axis
<!DOCTYPE html>
<html>
<head>
<style>
.square {
background: darkturquoise;
border-radius: 5px;
height: 100px;
margin: 100px;
width: 100px;
}
.square:hover {
transform: scale(2);
}
</style>
</head>
<body>
<div class="square">
</div>
</body>
</html>
2. rotate
With the rotate value, the element rotates clockwise or counterclockwise
by a specified number of degrees.
A positive value, such as 90deg, rotates the element clockwise, while a
negative value, such as -90deg, rotates it counterclockwise.
You can rotate more than a full rotation with numbers over than 360, such as
1080deg, for three full rotations.
<!DOCTYPE html>
<html>
<head>
3. Translate
The translate value moves an element left/right and up/down. The
movement is based on the parameters given for the X (horizontal) Y
(vertical) axes.
A positive X value moves the element to the right, while a negative X moves
the element to the left. A positive Y value moves the element downwards and a
negative Y value, upwards.
In this example, the element will move 20 pixels to the right and 20 pixels
down.
<!DOCTYPE html>
<html>
<head>
<style>
.square2 {
background: #FA54DE;
transition: 2s;
height: 100px;
margin: 100px;
width: 100px;
position:absolute;
.square2:hover{
transform: translate(100px,100px);
}
</style>
</head>
<body>
<div class="square2">
</div>
</body>
</html>
4. Skew
With the skew value, the element skews (or tilts) one direction or the other
based on the values given for the X and Y axes.
A positive X value tilts the element left, while a negative X value tilts it right.
A positive Y value tilts the element down, and a negative Y value tilts is up. Or
use a shorthand to include both X and Y properties:
div {
transform: skewX(25deg);
transform: skewY(10deg);
transform: skew(25deg, 10deg);
}
div {
transition: transform 1s;
}
div:hover {
transform: skewX(-20px);
}
5. Matrix
The matrix() method combines all the 2D transform methods into one.
The matrix() method take six parameters, containing mathematic functions,
which allows you to rotate, scale, move (translate), and skew elements.
The parameters are as follow:
matrix(scaleX(),skewY(),skewX(),scaleY(),translateX(),translateY())
Example
div {
transform: matrix(1,2,3,4,5,6);
}
CSS 3D Transforms
Transform Properties
The following table lists all the 3D transform properties:
Property Description
backface-visibility Defines whether or not an element should be visible when not facing the
screen
3D Transform Methods
Function Description
translateX(x) Defines a 3D translation, using only the value for the X-axis
translateY(y) Defines a 3D translation, using only the value for the Y-axis
CSS transitions allows you to change property values smoothly, over a given duration.
Transition properties:
transition
transition-delay
transition-duration
transition-property
transition-timing-function
transition- transition-timing-function:
timing- linear|ease|ease-in|ease-out|ease-
Specifies the speed curve of the
function in-out|step-start|step-
transition effect
end|steps(int,start|end)|cubic-
bezier(n,n,n,n)|initial|inherit;
Note: If the duration part is not specified, the transition will have no effect, because the default
value is 0.
The following example shows a 100px * 100px red <div> element. The <div> element has also
specified a transition effect for the width property, with duration of 2 seconds:
Example
div {
width: 100px;
height: 100px;
background: red;
transition: width 2s;
}
The transition effect will start when the specified CSS property (width) changes value.
Now, let us specify a new value for the width property when a user mouses over the <div>
element:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
div:hover {
width: 300px;
}
</style>
</head>
<body>
<p>Hover over the div element below, to see the transition effect:</p>
<div></div>
<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>
</body>
</html>
Notice that when the cursor mouses out of the element, it will gradually change
back to its original style.
<!DOCTYPE html>
<html>
<head>
<style>
div {
div:hover {
width: 300px;
}
</style>
</head>
<body>
<p>Hover over the div elements below, to see the different speed curves:</p>
<div id="div1">linear</div><br>
<div id="div2">ease</div><br>
<div id="div3">ease-in</div><br>
<div id="div4">ease-out</div><br>
<div id="div5">ease-in-out</div><br>
<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier
versions.</p>
</body>
</html>
The transition-delay property specifies a delay (in seconds) for the transition effect.
The following example has a 1 second delay before starting:
Example
Transition + Transformation
Example
div {
transition: width 2s, height 2s, transform 2s;
}
The CSS transition properties can be specified one by one, like this:
Example
div {
transition-property: width;
transition-duration: 2s;
transition-timing-function: linear;
transition-delay: 1s;
}
Example
div {
transition: width 2s linear 1s;
}
CSS animations make it possible to animate transitions from one CSS style configuration to
another.
There are three key advantages to CSS animations over traditional script-driven animation
techniques:
They’re easy to use for simple animations; you can create them without even having to
know JavaScript.
The animations run well, even under moderate system load. Simple animations can often
perform poorly in JavaScript. The rendering engine can use frame-skipping and other
techniques to keep the performance as smooth as possible.
Letting the browser control the animation sequence lets the browser optimize
performance and efficiency by, for example, reducing the update frequency of animations
running in tabs that aren't currently visible.
To create a CSS animation sequence, you style the element you want to animate with the
animation property or its sub-properties.
This lets you configure the timing, duration, and other details of how the animation
sequence should progress.
This does not configure the actual appearance of the animation, which is done using the
@keyframes at-rule as described in Defining the animation sequence using keyframes
below.
1. animation-name
2. animation-duration
3. animation-timing-function
4. animation-delay
5. animation-iteration-count
6. animation-direction
7. animation-fill-mode
8. animation-play-state
animation- animation-iteration-count:
Specifies how many times an animation
iteration- number|infinite|initial|inherit;
should be played
count
animation- animation-direction:
Specifies whether or not the animation
direction normal|reverse|alternate|alternate-
should play in reverse on alternate cycles
reverse|initial|inherit;
Once you’ve configured the animation’s timing, you need to define the appearance of the
animation. This is done by establishing two or more keyframes using the @keyframes
at-rule.
o Each keyframe describes how the animated element should render at a given time
during the animation sequence.
Since the timing of the animation is defined in the CSS style that configures the
animation, keyframes use a <percentage> to indicate the time during the animation
sequence at which they take place.
o 0% indicates the first moment of the animation sequence, while 100% indicates
the final state of the animation.
Because these two times are so important, they have special aliases: from and to. Both are
optional.
o If from/0% or to/100% is not specified, the browser starts or finishes the
animation using the computed values of all attributes.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background-color: red;
position: relative;
animation-name: example;
animation-duration: 4s;
animation-iteration-count:infinite;
}
@keyframes example {
0% {background-color:red; left:0px; top:0px;}
25% {background-color:yellow; left:200px; top:0px;}
50% {background-color:blue; left:200px; top:200px;}
75% {background-color:green; left:0px; top:200px;}
100% {background-color:red; left:0px; top:0px;}
}
</style>
</head>
<body>
<div></div>
</body>
</html>
*********************
Features of JavaScript
JavaScript is an open source scripting language.
It is lightweight.
It creates network-centric applications.
It is platform independent.
It validates form data.
It reduces server load.
Advantages of JavaScript
JavaScript saves server traffic.
It performs the operations very fast.
It is simple to learn and implement.
It is versatile.
JavaScript pages are executed on the client side.
JavaScript extends its functionality to the web pages.
Disadvantages of JavaScript
JavaScript cannot be used for networking applications.
It doesn't have any multithreading or multiprocessor capabilities.
It has security issues being a client-side scripting language.
What is a script?
Script is a small, embedded program.
The most popular scripting languages on the web are, JavaScript or
VBScript.
HTML does not have scripting capability, you need to use <script> tag.
The <script> tag is used to generate a script.
The </script> tag indicates the end of the script or program.
Example : Type attribute
<script type = “text/javascript”>
document.write(“TutorialRide”);
</script>
The 'type' attribute indicates which script language you are using with
the type attribute.
Types of Scripts
1. Client-Side Scripting
2. Server-Side Scripting
Client-Side Scripting
Client-Side Scripting is an important part of the Dynamic HTML
(DHTML).
JavaScript is the main client-side scripting language for the web.
The scripts are interpreted by the browser.
Client-Side scripting is used to make changes in the web page after
they arrive at the browser.
It is useful for making the pages a bit more interesting and user-
friendly.
It provides useful gadgets such as calculators, clocks etc.
It enables interaction within a web page.
It is affected by the processing speed of the user's computer.
Server-Side Scripting
Server-Side Scripting is used in web development.
The server-side environment runs a scripting language which is called
a web server.
Server-Side Scripting is used to provide interactive web sites.
It is different from Client-Side Scripting where the scripts are run
by viewing the web browser, usually in JavaScript.
It is used for allowing the users to have individual accounts and
providing data from databases.
It allows a level of privacy, personalization and provision
of information that is very useful.
It includes ASP.NET and PHP.
It does not rely on the user having specific browser or plug-in.
It is affected by the processing speed of the host server.
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!-- document.write("Hello World!") //-->
</script>
</body>
</html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
document.write(10 + 10);
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");
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");
After the declaration shown above, the variables are empty (they have no
values yet). However, you can also assign values to the variables when you
declare them:
var x=5;
var carname="Volvo";
After the execution of the statements above, the variable x will hold the
value 5, and carname will hold the value
Volvo.
If you assign values to variables that have not yet been declared, the
variables will automatically be declared. These statements:
10
After the execution of the statements above, the variable x will still have the
value of 5. The value of x is not reset (or cleared) when you redeclare it.
11
% Modulus (Reminder)
++ Increment
-- Decrement
Comparison Operators
Operator Description
== Equal To
=== Exactly Equal To
!= Not Equal To
< Less Than
> Greater Than
<= Less Than or Equal To
>= Greater Than or Equal To
Assignment Operators
Operator Description
= Simple Assignment
+= Add and Assignment
-= Subtract and Assignment
*= Multiply and Assignment
/= Divide and Assignment
%= Modulus and Assignment
Logical Operators
Operator Description
&& Logical AND
|| Logical OR
! Logical NOT
12
Special Operators
Operator Description
NEW Creates an instance of an object type.
DELETE Deletes property of an object.
DOT(.) Specifies the property or method.
VOID Does not return any value. Used to return a URL with no value.
1) If Statement
IF statement is a conditional branching statement.
In 'IF' statement, if the condition is true a group of statement is executed.
And if the condition is false, the following statement is skipped.
if(condition)
{
//Statement 1;
//Statement 2;
}
13
2) If – Else Statement
If – Else is a two-way decision statement.
It is used to make decisions and execute statements conditionally.
14
Syntax : If statement
15
16
Output
3) Switch Statement
Switch is used to perform different actions on different conditions.
It is used to compare the same expression to several different values.
17
18
Output:
19
4) For Loop
For loop is a compact form of looping.
It includes three important parts:
1. Loop Initialization
2. Test Condition
3. Iteration
All these three parts come in a single line separated by semicolons(;).
Flow Diagram of 'For' Loop
Syntax switch(expression)
{
case condition 1:
//Statements; break;
case condition 2:
//Statements; break;
case condition 3:
//Statements; break;
.
.
case condition n:
//Statements; break;
default:
//Statement;
}
Example : Palindrome Program using For Loop
<html>
<body>
<script
type="text/javascript">
function palindrome()
{
var revstr = " ";
var strr = document.getElementById("strr").value;
var i = strr.length;
for(var j=i; j>=0; j--)
{
20
Output:
5) For-in Loop
21
6) While Loop
While loop is an entry-controlled loop statement.
It is the most basic loop in JavaScript.
It executes a statement repeatedly as long as expression is true.
Once the expression becomes false, the loop terminates.
Flow Diagram of While Loop
Syntax
7) Do-While Loop
Do-While loop is an exit-controlled loop statement.
Similar to the While loop, the only difference is condition will be checked at
the end of the loop.
The loop is executed at least once, even if the condition is false.
while (condition)
{
//Statements;
}
23
Output:
0
1
2
3
4
5
8) Break Statement
24
Syntax
do
{
//Statements;
}
9) Continue Statement
Continue statement causes the loop to continue with the next iteration.
It skips the remaining code block.
Syntax:
break;
25
User-defined Functions
User-defined function means you can create a function for your own use.
You can create yourself according to your need.
In JavaScript, these functions are written in between the <HEAD> tag of
the HTML page.
26
Example :
function myFunction(p1, p2)
{
return p1 * p2; // The function returns the product of p1 and p2
}
Function Invocation
The code inside the function will execute when "something" invokes
(calls) the function:
When an event occurs (when a user clicks a button)
When it is invoked (called) from JavaScript code
Automatically (self invoked)
Function Return
When JavaScript reaches a return statement, the function will stop
executing.
If the function was invoked from a statement, JavaScript will
"return" to execute the code after the invoking statement.
Functions often compute a return value. The return value is
"returned" back to the "caller―.
27
Example:
<html>
<head>
<script>
function toCelsius(f) {
var res=(5/9) * (f-32);
document.write(f+ " Degree Fahrenheit is = "+Math.floor(res,2)+" Degree
Celsius");
}
</script>
</head>
<body>
<h2>JavaScript Functions</h2>
<button onclick='toCelsius(98);'>Click Here</button>
</body>
</html>
28
Multidimensional Array
var arr2 = [
[1, 2, 3] ,
['a', 'b', 'c']
,
]; ['x', 'y', 'z']
function show_array(arr)
{
for (var i = 0; i < arr.length; i++ )
{
document.write(array[i]);
document.write('<br/>');
29
Array Properties
Array
Description
Properties
Constructor It returns a reference to the array function that created the
object.
Index It represents the zero-based index of the match in the
string.
Length It reflects the number of elements in an array.
Input It presents only an array created by regular expression
matches.
Prototype It allows you to add properties and methods to an object.
Array Methods
Methods Description
concat() It returns a new array comprised of this array joined with other
arrays and values.
every() It returns true if every element in this array satisfies the
provided testing function.
filter() It creates a new array with all the elements of this array for which
the provided filtering function returns true.
indexOf() It returns the first index of an element within the array equal to
the specified value.
join() It joins all elements of an array into a string.
pop() It removes the last element from an array and returns that
element.
push() It adds one or more elements to the end of an array and returns
the new length of the array.
reverse() It reverses the order of the elements of an array.
sort() It represents the source code of an object.
30
Output:
31
Syntax:
Definition: DOM
The W3C Document Object Model (DOM) is a platform and language-
neutral interface that allows programs and scripts to dynamically access
and update the content, structure, and style of a document."
<html>
<head>
<title>My Page</title>
32
</head>
<body>
<h1> Hello! </h1>
</body>
</html>
2.2: JavaScript DOM Model
Document
<head>
<body> <title>
<h1>
At the top level, there is an html node, with two children: head
and body, among which only head has a child tag title.
HTML tags are element nodes in DOM tree, pieces of text become
text nodes. Both of them are nodes, just the type is different.
My PageHello!
ACCESSING DOM:
The HTML DOM can be accessed with JavaScript (and with other
programming languages).
In the DOM, all HTML elements are defined as objects.
With the object model, JavaScript gets all the power it needs to
create dynamic HTML:
JavaScript can change all the HTML elements in the page
JavaScript can change all the HTML attributes in the page
JavaScript can change all the CSS styles in the page
JavaScript can remove existing HTML elements and attributes
JavaScript can add new HTML elements and attributes
33
There are many types of nodes in the DOM document tree that specifies
what kind of node it is. Every Object in the DOM document tree has
properties and methods defined by the Node host object.
The following table lists the non method properties of Node object.
The following table lists the node types commonly encountered in HTML
documents and the nodeType value for each one.
34
Method Description
document.getElementById() Find an element by element id
document.getElementsByTagName() Find elements by tag name
document.getElementsByClassName() Find elements by class name
35
Reacting to Events
A JavaScript can be executed when an event occurs, like when a
user clicks on an HTML element.
To execute code when a user clicks on an element, add
JavaScript code to an HTML event attribute:
onclick=JavaScript
Examples of HTML events:
When a user clicks the mouse
When a web page has loaded
When an image has been loaded
When the mouse moves over an element
When an input field is changed
When an HTML form is submitted
37
38
<html>
<body>
<script>
function validateemail()
{
var a =
document.myform.email.value; var
atposition = a.indexOf("@");
var dotposition = a.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 ||
dotposition+2>=a.length)
{
alert("Please Enter a valid E-mail
Id"); return false;
}
}
</script>
</body>
<body>
<form name="myform" method="post" action="validpage.html"
onsubmit="return validateemail();">
Enter Your Email Id: <input type="text" name="email"><br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
<html>
<body>
<script type="text/javascript">
alert("You are a Valid User
!!!");
</script>
</body>
</html>
39
<script type="text/javascript">
var ck_name = /^[A-Za-z0-9 ]{3,20}$/;
var ck_email = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-
z]{2,6}(?:\.[a-z]{2})?)$/i
var ck_username = /^[A-Za-z0-9_]{1,20}$/;
var ck_password = /^[A-Za-z0-9!@#$%^&*()_]{6,20}$/;
function validate(){
var name = form.name.value;
var email =
form.email.value;
var username =
form.username.value; var password =
form.password.value; var gender =
form.gender.value;
var errors = [];
40
if (!ck_email.test(email)) {
errors[errors.length] = "You must enter a valid email address.";
}
if (!ck_username.test(username)) {
errors[errors.length] = "You must enter valid UserName with no special
char .";
}
if (!ck_password.test(password)) {
errors[errors.length] = "You must enter a valid Password min 6 char.";
}
if (gender==0) {
errors[errors.length] = "Select Gender";
}
if (errors.length > 0) {
reportErrors(errors);
return false;
}
return true;
}
function reportErrors(errors){
var msg = "Please Enter Valide Data...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
</head>
41
42
2.5: Form
Event Handlers: Functions that handle events are called event handlers.
They contain the script that gets executed in response to the events.
Event
handler Applies to: Triggered when:
onAbort Image The loading of the image is
cancelled.
onBlur Button, Checkbox, The object in question loses
Password, Radio, focus (e.g. by clicking outside it
Reset, Select, Submit, or pressing the TAB key).
Text, TextArea,
Window
onChange Select, Text, TextArea The data in the form element is
changed by the
user.
onClick Button, Checkbox, The object is clicked on.
Link, Radio, Reset,
Submit
onDblClick Document, Link The object is double-clicked on.
43
44
<form onsubmit="handleSubmit();">
<input type="text" onselect="window.alert('text selected')" /><br />
45
<html>
<head>
<script
type="text/javascript">
function time()
{
var d = new Date();
var ty = d.getHours() + ":"+d.getMinutes()+":"+d.getSeconds();
document.frmty.timetxt.value=ty;
setInterval("time()",1000)
}
</script>
46
Output:
<html>
<body>
<script>
function validateform()
{
var uname=document.myform.name.value;
var upassword=document.myform.password.value;
if (uname==null || uname=="")
{
alert("Name cannot be left
blank"); return false;
}
else if(upassword.length<6)
{
alert("Password must be at least 6 characters long.");
return false;
}
}
47
<html>
<body>
<script type="text/javascript">
alert("You are a Valid User
!!!");
</script>
</body>
</html>
Output:
48
2.6: Event
Syntax error:
Syntax errors, also called parsing errors, occur at compile time
in traditional programming languages and at interpret time in
JavaScript.
For example, the following line causes a syntax error because it is missing
a closing parenthesis.
<script type = "text/javascript">
<!--
window.print(;
//-->
</script>
49
Logical error:
Logic errors can be the most difficult type of errors to track down. These
errors are not the result of a syntax or runtime error. Instead, they occur
when you make a mistake in the logic that drives your script and you do not
get the result you expected.
You cannot catch those errors, because it depends on your business
requirement what type of logic you want to put in your program.
Runtime Error:
Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation).
For example, the following line causes a runtime error because here the
syntax is correct, but at runtime, it is trying to call a method that does not
exist.
What is an Exception?
An exception signifies the presence of an abnormal condition which
requires special operable techniques.
In programming terms, an exception is the anomalous code that
breaks the normal flow of the code. Such exceptions require
specialized programming constructs for its execution.
50
Error Object
When a runtime error occurs, it creates and throws an Error object. Such
an object can be used as a base for the user-defined exceptions too. An error
object has two properties:
51
The try block must be followed by either exactly one catch block or
one finally block (or one of both). When an exception occurs in
the try block, the exception is placed in e and the catch block is executed.
The optional finally block executes unconditionally after try/catch.
Example 1:
<!DOCTYPE html>
<html>
<body>
52
<p id="p01"></p>
<script>
function myFunction()
{ var message, x;
message = document.getElementById("p01");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "is empty";
if(isNaN(x)) throw "is not a
number"; x = Number(x);
if(x > 10) throw "is too
high"; if(x < 5) throw "is too
low";
}
catch(err) {
message.innerHTML = "Input " + err;
}
finally {
document.getElementById("demo").value = "";
}
}
</script>
</body>
</html>
53
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Errors</h2>
<p>You cannot convert a number to upper case:</p>
<p id="demo"></p>
<script>
var num = 1;
try {
num.toUpperCase();
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
</script>
</body>
</html>
54
Output
You can use throw statement to raise your built-in exceptions or your
customized exceptions. Later these exceptions can be captured and you can
take an appropriate action.
Example:
<script type = "text/javascript">
<!--
try {
/
/
C
o
d
e
t
o
55
<html>
<head>
</script>
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.
56
1) Date
2) Math
3) String, Number, Boolean
4) RegExp
5) window (Global Obejct)
1) Math Object
Math object is a built-in static object.
It is used for performing complex math operations.
Math Properties
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.
57
Output
58
Output:
E Value is :2.718281828459045
LN2 Value is
:0.6931471805599453 LN10 Value
is :2.302585092994046 PI Value is
:3.141592653589793
2) 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:
59
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-
60
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.
Output:
61
Example:
var s = new String(string);
String Properties
Properties Description
length It returns the length of the string.
prototype It allows you to add properties and methods to an object.
constructor It returns the reference to the String function that created the
object.
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.
slice() It extracts a session of a string and returns a new string.
62
Output:
63
Syntax
Use the following syntax to create a boolean object.
var val = new Boolean(value);
5) Number Object
Method Description
toExponential(x) Converts a number into an exponential notation
toFixed(x) Formats a number with x numbers of digits after the
decimal point
64
Example:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript toPrecision() Method </title>
</head>
<body>
<script type = "text/javascript">
var num = new Number(7.123456);
</script>
</body>
</html>
65
Method Description
alert() Displays an alert box with a message and an OK button
blur() Removes focus from the current window
clearInterval() Clears a timer set with setInterval()
clearTimeout(
Clears a timer set with setTimeout()
)
close() Closes the current window
Displays a dialog box with a message and an OK and a
confirm()
Cancel button
createPopup() Creates a pop-up window
focus() Sets focus to the current window
moveBy() Moves a window relative to its current position
moveTo() Moves a window to the specified position
open() Opens a new browser window
print() Prints the content of the current window
prompt() Displays a dialog box that prompts the visitor for input
resizeBy() Resizes the window by the specified pixels
resizeTo() Resizes the window to the specified width and height
scroll()
scrollBy() Scrolls the content by the specified number of pixels
scrollTo() Scrolls the content to the specified coordinates
66
Example:
<!DOCTYPE HTML>
<html>
<head>
<title>JavaScript Window Object Methods</title>
<script type="text/javascript">
var mywin;
function openNewWin(url)
{
var wid =
500; var hei =
200;
var winFeat = "width = " + wid + ", height = " + hei + " ,
status, resizable";
myWin = window.open(url, "subWind", winFeat);
}
function disp_alert()
{
alert("Hi, This is an alert box.");
}
function close_win()
{
if(window.confirm("Do you really want to close the browser
?"))
window.close();
}
</script>
</head>
67
68
</body>
</html>
Output
69
Output:
Addition: 5
2.8:
HTML 4.0
HTML is a client-side markup language, which is a core component of the
DHTML. It defines the structure of a web page with various defined basic
elements or tags.
CSS
CSS stands for Cascading Style Sheet, which allows the web users or
developers for controlling the style and layout of the HTML elements on the
web pages.
JavaScript
JavaScript is a scripting language which is done on a client-side. The
various browser supports JavaScript technology. DHTML uses the
JavaScript technology for accessing, controlling, and manipulating the
70
HTML elements. The statements in JavaScript are the commands which tell
the browser for performing an action.
DOM
DOM is the document object model. It is a w3c standard, which is a
standard interface of programming for HTML. It is mainly used for defining
the objects and properties of all elements in HTML.
Uses of DHTML
It is used for designing the animated and interactive web pages that
are developed in real-time.
DHTML helps users by animating the text and images in their
documents.
It allows the authors for adding the effects on their pages.
It also allows the page authors for including the drop-down menus or
rollover buttons.
This term is also used to create various browser-based action games.
It is also used to add the ticker on various websites, which needs
to refresh their content automatically.
Difference between HTML and DHTML
3. This markup language creates static 3. This concept creates dynamic web
web pages. pages.
4. It does not contain any server-side 4. It may contain the code of server-
71
5. The files of HTML are stored with 5. The files of DHTML are stored with
the .html or .htm extension in a the .dhtm extension in a system.
system.
<html>
<head>
<title>
changes the particular HTML element example
</title>
</head>
<body>
<p id="demo"> This text changes color when click on the following different buttons. </p>
<button onclick="change_Color('green');"> Green </button>
<button onclick="change_Color('blue');"> Blue </button>
<script type="text/javascript">
function change_Color(newColor) {
var element = document.getElementById('demo').style.color = newColor;
}
</script>
</body>
</html>
72
2.9:
DHTML
JSON stands for Javascript Object Notation. JSON is a text-based data
format that is used to store and transfer data.
For example,
// JSON syntax
{
"name": "John",
"age": 22,
"gender":
"male",
73
JSON was derived from JavaScript. So, the JSON syntax resembles
JavaScript object literal syntax. However, the JSON format can be accessed
and be created by other programming languages too.
74
Example "name":
JSON Object
2.10: JSON introduction – Syntax – Function Files
The JSON object is written inside curly braces { }. JSON objects can contain multiple key/value pai
JSON Array
JSON array is written inside square brackets [ ] . For example,
// JSON array
[ "apple", "mango", "banana"]
75
"name":
"John", "age":
22,
"hobby": {
"reading" : true,
"gaming" : false,
"sport" :
"football"
},
"class" : ["JavaScript", "HTML", "CSS"]
}
/
/
J
S
O
[]
76
The key in key/value pair should be in The key in key/value pair can be
double quotes. without double quotes.
JSON can be created and used by other JavaScript objects can only be
programming languages. used in JavaScript.
// json object
Converting JSON to=JavaScript
const jsonData '{ "name":Object
"John", "age": 22 }';
YoucanconvertJSONdatatoaJavaScriptobjectusingthebuilt- infunction. For example,
// converting to JavaScript object const obj = JSON.parse(jsonData);
JSON.parse()
// JavaScript object
Converting JavaScript
const Object to JSON
jsonData = { "name": "John", "age": 22 };
YoucanalsoconvertJavaScriptobjectstoJSONformatusingthe
// converting to JSON JavaScript built-infunction. For example,
77
JSON.stringify()
JSON Example
This example reads a menu from myTutorials.js, and displays the menu in
a web page:
JSON Example
<div id="id01"></div>
<script>
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i<arr.length; i++) {
out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
78
<script src="myTutorials.js"></script>
Example Explained
Create a function myFunction() that loops the array objects, and display
the content as HTML links:
myFunction()
function myFunction(arr) {
var out = "";
79
Calling myFunction()
myFunction([
{
"display": "JavaScript Tutorial",
"url": "https://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "https://www.w3schools.com/css/default.asp"
}
]);
80
myTutorials.js
myFunction([
{
"display": "JavaScript Tutorial",
"url": "https://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "https://www.w3schools.com/css/default.asp"
}
]);
Add the external script to your page (instead of the function call):
81
SERVER-SIDE PROGRAMMING
Server-Side Programming means that writing scripts that are executed on
the server and are then translated into HyperText Markup Language (HTML)
which can be viewed by all web browsers.
3.2: Servlets
Servlets are Java programs that run on a web server and act as a middle
layer between a requests coming from a web browser or other HTTP client
and databases or applications on the server.
Using servlets,
We can collect input from users through web page forms, present
records from a databases (or) another source and create web pages
dynamically.
We can develop sites with secure access, interact with DB, and
maintain unique session info of each client.
1. Static Response: HTML document retrieved from the file system and
returned to the client is called static response.
2. Dynamic Response: HTML document is generated by a program in
response to an HTTP request.
1. Client
In this architecture, the web browser acts as a Client. Client or user
connected with a web browser. The client is responsible for sending requests
or HttpRequest to web server and processing responses received by the Web
server.
2. Web Server
Web server controls how web user access hosted files and it is responsible
for processing user request and responses. Here server is a software that
understand URLs and HTTP protocol. Whenever browser needs to request
file on the webserver, it process client request using HTTP request, if it finds
requested file sends it back to browser through HTTP Response. There are
two types’ web servers Static and Dynamic webservers.in static web server
sends the file as it is but in dynamic webserver hosted file is updated before
it is sent to the browser.
3. Web Container
Web container is the component in the webserver it interacts with Java
servlets. A web container is responsible for managing the lifecycle of servlets
and it also performs the URL mapping task. Web container handles the
requests of servlets, JSP and other files at the server-side. The important
tasks performed by servlets are loading and unloading servlets, creating and
managing requests and response objects and performs the overall tsk of
servlet management.
Following are the steps how servlet request has been processed consider the
above diagram.
The client sends a request.
Web Server accepts the request and forwards it to the web container.
Web container searches web.xml file for request URL pattern and gets
the address of the servlet.
Advantages
Below are some important advantages of the servlet as follows:
Servlets are server independent, as they are compatible with any web
server. Compared to other server-side web technologies like ASP and
JavaScript these are server-specific.
Servlets are protocol-independent i.e. it supports FTP, SMTP, etc.
Mainly it provides extended support to HTTP protocol functionality.
Disadvantages
Designing a servlet can be pretty laborious.
Exceptions need to be handled while designing a servlet since they are
not thread-safe.
Developers may need additional skills to program a servlet.
A servlet life cycle can be defined as the entire process from its
creation till the destruction.
1) init()
2) service()
3) destroy()
This method is called when the servlet is first created. It is called only once
during its lifecycle and not called again for each user request. So, it is used
for one-time initializations, just as with the init method of applets.
When a user invokes a servlet, a single instance of each servlet gets created,
with each user request resulting in a new thread that is handed off to doGet
or doPost as appropriate. The init() method simply creates or loads some
data that will be used throughout the life of the servlet.
The service() method is the main method to perform the actual task. The
servlet container (i.e. web server) calls the service() method to handle
requests coming from the client( browsers) and to write the formatted
response back to the client.
Each time the server receives a request for a servlet, the server spawns a
new thread and calls service. The service() method checks the HTTP request
type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut,
doDelete, etc. methods as appropriate.
The service () method is called by the container and service method invokes
doGe, doPost, doPut, doDelete, etc. methods as appropriate. So you have
nothing to do with service() method but you override either doGet() or
doPost() depending on what type of request you receive from the cl ient.
The doGet() and doPost() are most frequently used methods with in each
service request. Here are the signature of these two methods.
A GET request results from a normal request for a URL or from an HTML
form that has no METHOD specified and it should be handled by doGet()
method.
A POST request results from an HTML form that specifically lists POST as
the METHOD and it should be handled by doPost() method.
The destroy() method is called only once at the end of the life cycle of a
servlet. This method gives your servlet a chance to close database
connections, halt background threads, write cookie lists or hit counts to
disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage
collection. The destroy method definition looks like this:
out.println("<html>");
out.println("</html>");
}catch(Exception e){}
}
}
}
Servlets - Examples
Servlets are Java classes which service HTTP requests and implement the
javax.servlet.Servlet interface.
Web application developers typically write servlets that extend
javax.servlet.http.HttpServlet, an abstract class that implements the Servlet
interface and is specially designed to handle HTTP requests.
10
{
// Set response content type
response.setContentType("text/html");
Output:
Finally type http://localhost:8080/HelloWorld in browser's address box. If
everything goes fine, you would get following result:
Servlet has methods to access data contained in HTTP Request (URL) sent to
the server from the browser.
The Query String portion of the HTTP request is so called parameter
data.
For example,
http://www.example.com/servlet/PrintThis?name=Raj&color=Red
where,
the portion after the ? is called a query string.
11
The following methods are used to process these parameter data in servlets.
The following program explains how to process these parameter names and
values as well as path of the resource using servlet.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class NewServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType("text/html”);
PrintWriter out = response.getWriter();
try {
12
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet NewServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("Servlet file NewServlet is at: " + request.getContextPath());
Enumeration para1=request.getParameterNames();
while(para1.hasMoreElements())
{
out.println("Parameter name:"+para1.nextElement());
}
String name = request.getParameter("name");
String id = request.getParameter("id");
out.println("Name:" + name);
out.println("Id:" + id);
out.println("</body>");
out.println("</html>");
}catch(Exception e){}
}
}
}
13
Output:
The method attribute specifies how to send form-data (the form-data is sent
to the page specified in the action attribute).
The form-data can be sent as URL variables (with method="get") or as HTTP
post transaction (with method="post").
Notes on GET:
It is used to process the query string which is part of URL
Appends form-data into the URL in name/value pairs
The length of a URL is limited (about 3000 characters)
It is recommended when parameter data is not stored but used only to
request information.
Never use GET to send sensitive data! (will be visible in the URL)
Useful for form submissions where a user wants to bookmark the
result
GET is better for non-secure data, like query strings in Google
Notes on POST:
It is used to process the query string as well as to store the data on
server.
Appends form-data inside the body of the HTTP request (data is not
shown in URL)
Has no size limitations.
It is recommended if parameter data is intended to cause the server to
update stored data
14
Most browsers will warn you if they are about to resubmit POST data
to avoid duplicate updates
Form submissions with POST cannot be bookmarked
BASIS FOR
GET POST
COMPARISON
Example:
The following program explains how to send the data to server from a web
page and the same how to receive it from the server.
<html>
<head>
</head>
15
<body>
<pre>
<form action="NewServlet" method="post">
First Name: <input type="text" name="t1" />
Last Name: <input type="text" name="t2" />
Age: <input type="text" name="t3" />
E-mail:<input type="text" name="t4" />
<input type="submit" value="Submit" />
<form>
</pre>
</body>
</html>
Servlet for processing the data coming from this web page
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class NewServlet extends HttpServlet
{
public void goPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet NewServlet</title>");
out.println("</head>");
out.println("<body>");
String s1 = request.getParameter("t1");
String s2 = request.getParameter("t2");
String s3 = request.getParameter("t3");
String s4 = request.getParameter("t4");
out.println("First Name:" + s1);
out.println("Last Name:" + s2);
16
out.println("Age:" + s3);
out.println("E-mail:" + s4);
out.println("</body>");
out.println("</html>");
} catch(Exception e) {}
}
}
Output
Login.html
<html>
<body>
<form action="login" method="get">
<table>
<tr>
<td>User</td>
<td><input name="user" /></td>
</tr>
<tr>
<td>password</td>
<td><input name="password" /></td>
</tr>
</table>
<input type="submit" />
</form>
</body>
</html>
17
create a Servlet which receives the request in /login , which is the indicated
direction in the action attribute of the tag <form> of login.html
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
protected void doGet(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException
{
String user = req.getParameter("user");
String pass = req.getParameter("password");
if ("balamurugan".equals(user) && "bala1234".equals(pass))
{
response(resp, "login ok");
}
else
{
response(resp, "invalid login");
}
}
private void response(HttpServletResponse resp, String msg)
throws IOException
{
PrintWriter out = resp.getWriter();
out.println("<html><body>");
out.println(msg);
out.println("</body></html>");
}
}
We compilate this Servlet and we include LoginServlet.class in the folder
/WEB-INF/classes. We modify web.xml to link /login with this Servlet.
web.xml
<web-app>
18
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class> hello </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login-servlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
We restart the server, open the page login.html, write an "x" in user, write
an "x" in password and click on the submit button.
19
<html>
<body>
<form action="login" method="post">
<table>
<tr><td>User</td> <td><input name="user" /></td></tr>
<tr><td>password</td> <td><input name="password" /></td></tr>
</table>
<input type="submit" />
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
20
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
protected void doPost(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException
{
String user = req.getParameter("user");
String pass = req.getParameter("password");
if ("balamurugan".equals(user) && "bala1234".equals(pass))
{
response(resp, "login ok");
}
else
{
response(resp, "invalid login");
}
}
private void response(HttpServletResponse resp, String msg)
throws IOException
{
PrintWriter out = resp.getWriter();
out.println("<html><body>");
out.println(msg);
out.println("</body></html>");
}
}
21
22
1) Cookies
2) URL Rewriting
3) Hidden Form Field
4) HttpSession
1. Cookies
23
(ii) The server then replies in the form of HTTP response, session id is
given in the form of cookie.
Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
1. Non-persistent cookie
It is valid for single session only. It is removed each time when user closes
the browser.
2. Persistent cookie
It is valid for multiple session. It is not removed each time when user closes
the browser. It is removed only if user logout or sign out.
24
Advantage of Cookie
Simplest technique of maintaining the state.
Cookie are maintained at client side so they do not give any burden to
server.
All server side technology and all web server, application servers
support cookies.
Presistent cookies can remember client data during session and after
session with expiry time.
Limitation of Coockie
It will not work if cookie is disabled from the browser.
Cookies are text files, It does not provides security. Anyone can change
this file.
With cookies need client support that means if client disable the
coockies then it does not store the client location.
Cookies cannot store java objects as values, they only store text or
string.
25
Each time when web browser sends request back, then session_id value
can be used to keep track of the different web browsers.
This could be an effective way of keeping track of the session but clicking
on a regular (<a href=….>) hypertext link does not result in a form
submission, so hidden form fields also cannot support general session
tracking.
Hidden Form Field Advantage
Basic knowledge of html is enough to work with this technique.
It will always work whether cookie is disabled or not.
Hidden boxes resides in web pages of browser window so they do not
provide burden to the server.
This technique can be used along with all kind of web server or
application server.
Hidden Form Field Dis-Advantage
More complex than URL Rewriting.
It is maintained at server side.
Extra form submission is required on each pages.
Hidden form field can not store java object as values. They only store
text value
It Also increase network traffic because hidden boxes data travels over
the network along with request and response.
Hidden boxes does not provides data security because their data can be
view through view source option.
<form action="servlet1">
Name:<input type="text" name="userName"/> <br/>
<input type="submit" value="continue"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
26
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
27
out.close();
}
catch(Exception e){System.out.println(e);}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
28
3. URL Rewriting
In URL rewriting, we append a token or identifier to the URL of the
next Servlet or the next resource. We can send parameter name/value
pairs using the following format:
url?name1=value1&name2=value2&??
A name and a value is separated using an equal = sign, a parameter
name/value pair is separated from another parameter using the
ampersand(&). When the user clicks the hyperlink, the parameter
name/value pairs will be passed to the server. From a Servlet, we can
use getParameter() method to obtain a parameter value.
index.html
1. <form action="servlet1">
29
FirstServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class FirstServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse respon
se){
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. String n=request.getParameter("userName");
14. out.print("Welcome "+n);
15.
16. //appending the username in the query string
17. out.print("<a href='servlet2?uname="+n+"'>visit</a>");
18.
19. out.close();
20.
21. }catch(Exception e){System.out.println(e);}
22. }
23.
24. }
SecondServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
30
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse respon
se)
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. //getting value from the query string
14. String n=request.getParameter("uname");
15. out.print("Hello "+n);
16.
17. out.close();
18.
19. }catch(Exception e){System.out.println(e);}
20. }
21.
22.
23. }
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
14. <servlet-name>s2</servlet-name>
31
15. <servlet-class>SecondServlet</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
21. </servlet-mapping>
22.
23. </web-app>
4. HTTPSession Interface
1) bind objects
2) View and manipulate information about a session, such as the session
identifier, creation time, and last accessed time.
A. Creating a Session
32
C. Session Termination:
Methods Used:
i) setMaxInactiveInterval(int)
This method takes an integer argument representing a number of
seconds.
After the specified time elapses, the user’s session will expire.
ii) invalidate()
If the timer completes before the next request containing the session
ID is received, the server calls the invalidate() directly at any time in
order to terminate the running session.
Example:
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet(urlPatterns = {"/SessionServlet"})
public class SessionServlet extends HttpServlet {
@Override
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
What is PHP?
PHP is an acronym for "PHP: Hypertext Preprocessor"
PHP is a widely-used, open source server-side scripting language for
creating dynamic web pages.
PHP scripts are executed on the server.
PHP is platform independent and free to download and use.
HISTORY:
PHP was created by Rasmus Lerdorf to track users at his website.
In 1995, Lerdorf released it as a package called the “Personal Home Page
Tools”.
Two years later, PHP 2 features built-in database support and form
handling.
In 1997, PHP 3 was released with a rewritten parser, which substantially
increased performance and led to an explosion of PHP use.
The release of PHP 4 featured the new “Zend Engine” from Zend, a PHP
software company. This version was faster and more powerful than its
predecessor.
Currently, PHP 5 features the new “Zend Engine 2” which provides further
speed increases, exception handling and a new object-oriented
programming model.
FEATURES OF PHP:
1. PHP can generate dynamic page content.
2. PHP can create, open, read, write, delete, and close files on the server.
3. PHP can collect form data.
4. PHP can send and receive cookies.
5. PHP can add, delete, and modify data in your database.
1
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
6. PHP can be used to control user-access.
7. PHP can encrypt data.
8. With PHP you are not limited to output HTML. You can output images,
PDF files, and even Flash movies.
9. You can also output any text, such as XHTML and XML.
ADVANTAGES OF PHP:
Portability (Platform Independent) - PHP runs on various platforms
(Windows, Linux, UNIX, Mac OS X, etc.)
Performance - Scripts written in PHP executives faster than those written
in other scripting language.
Ease Of Use – It is easy to use. Its syntax is clear and consistent.
Open Source - PHP is an open source project –it may be used without
payment of licensing fees or investments in expensive hardware or
software. This reduces software development costs without affecting either
flexibility or reliability
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP supports a wide range of databases.
PHP is easy to learn and runs efficiently on the server side.
Community Support - One of the nice things about a community-supported
language like PHP is, accessing it offers to the creativity and imagination of
hundreds of developers across the world.
INSTALLING PHP:
To program PHP, follow the below three steps:
o install a web server (Any Web server capable of executing PHP codes)
o install PHP
o install a database, such as MySQL
The official PHP website (PHP.net) has installation instructions for PHP:
http://php.net/manual/en/install.php
2
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
"echo" – statement used to output the text on a web page:
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
COMMENTS IN PHP:
A comment in PHP code is a line that is not read/executed as part of the
program. Its only purpose is to be read by someone who is looking at the
code.
Comments can be used to:
Let others understand what you are doing
Remind yourself of what you did.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block that
spans over Multiple lines
*/
$x = 5 /* + 15 */ + 5;
3
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
echo $x;
?>
</body>
</html>
<?php
// all the echo statements are treated as same
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
</body>
</html>
Hello World!
Hello World!
Hello World!
My car is red
My house is
My boat is
4
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
4.1.3: PHP – VARIABLES
Declaring PHP variables: In PHP, a variable starts with the $ sign, followed by
the name of the variable.
Syntax: $variable_name
Initializing PHP variables: Variables are assigned with the = operator, with the
variable on the left-hand side and the expression to be evaluated or value on the
right. The value of a variable is the value of its most recent assignment.
Syntax: $variable_name= expression or value;
Example:
<html>
<head>
<title>Online PHP Script Execution</title>
</head>
<body>
<?php
$number = 10;
$text ="My variable contains the value of ";
print($text.$number);
?>
</body>
</html>
Output:
5
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
PHP VARIABLES SCOPE:
Global Scope:
A variable declared outside a function has a GLOBAL SCOPE and can only
be accessed outside a function:
Local Scope:
A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function.
Example:
<?php
$num1=1; // global variable
$x = 5; // global variable
$y = 10; // global variable
function myTest() {
$num1=11; // local variable
static $z=0;
$z++;
echo "z = ".$z."<br>"; // static variable retains the last changed value
global $x, $y;
$y = $x + $y;
echo "num1 inside function = ".$num1."<br>"; // prints 11
}
myTest();
mytest();
6
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
echo "x + y = ".$y."<br>"; // outputs 15
echo "num1 outside function= ".$num1; // prints 1
?>
z=1
num1 inside function = 11
z=2
num1 inside function = 11
x + y = 20
num1 outside function= 1
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
7
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
o echo can take multiple parameters (although such usage is rare)
while print can take one argument.
o echo is marginally faster than print.
The echo statement can be used with or without parentheses: echo or
echo().
The print statement can be used with or without parentheses: print or
print().
Example:
<?php
$txt1 = "Learn PHP";
$txt2 = "deitel.com";
$x = 5;
$y = 4;
echo "<h2>$txt1</h2>";
print "Study PHP at " . $txt2 . "<br>";
Output:
Learn PHP
Study PHP at deitel.com
X+Y=9
Variables can store data of different types, and different data types can do
different things.
Type Description
string Text enclosed in either single („ „) or double (“ “) quotes.
int, Integer Whole numbers (i.e., numbers without a decimal point)
float, double, real Real numbers (i.e., numbers containing a decimal point)
bool, boolean True or False
array Group of elements
8
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
object Group of associated data and methods
NULL No value
resource An external source – usually information from a database
PHP String:
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double
quotes.
Example: $str1=”Hello World”; $str2=‟Hello World‟;
PHP Integer:
An integer is a whole number (without decimals).
It is a number between -2,147,483,648 and +2,147,483,647.
Rules for integers:
An integer must have at least one digit (0-9)
An integer cannot contain comma or blanks
An integer must not have a decimal point
An integer can be either positive or negative
Integers can be specified in three formats: decimal (10-based),
hexadecimal (16-based - prefixed with 0x) or octal (8-based - prefixed
with 0)
Example: $x=5;
PHP Float:
A float (floating point number) is a number with a decimal point or a
number in exponential form.
Example: $x=41.45;
The PHP var_dump() function returns the data type and value.
PHP Boolean:
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
Booleans are often used in conditional testing.
PHP Array:
An array stores multiple values in one single variable.
Example: $cars = array("Volvo","BMW","Toyota");
PHP Object:
An object is a data type which stores data and information on how to
process that data.
9
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
In PHP, an object must be explicitly declared.
First we must declare a class of object. For this, we use the class keyword.
A class is a structure that can contain properties and methods:
PHP Resource:
The special resource type is not an actual data type.
It is the storing of a reference to functions and resources external to PHP.
A common example of using the resource data type is a database call.
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5985; // Integer variable
$y = 59.85; // float variable
$str1="Hello "; // string
$str2="World"; // string
$bool1=true; // boolean
$bool2=false; // boolean
$cars = array("Volvo","BMW","Toyota"); // array
<?php
10
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
// create an object
$herbie = new Car(); // creating object for car class
Output:
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$var1="114";
$var2=114.12;
$var3=114;
settype($var1,"double");
settype($var2,"integer");
settype($var3,"string");
?>
</body>
</html>
12
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
A valid constant name starts with a letter or underscore (no $ sign before
the constant name).
CREATING CONSTANTS:
o To create a constant, use the define() function.
o Syntax:
define (name, value, case-insensitive)
Parameters:
o name: Specifies the name of the constant
o value: Specifies the value of the constant
o Case-insensitive: Specifies whether the constant name should be
case-insensitive. Default is false.
Note: Unlike variables, constants are automatically global across the entire
script. The example below uses a constant inside a function, even if it is
defined outside the function.
Example:
<html>
<head><title>Logical Operators</title><head>
<body>
<?php
define("GREETING", "Welcome to php!");
function test()
{
13
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
echo constant("GREETING"); echo "<br/><br/>";
define("TUTORIALS", "www.deitel.com",true);
echo "Learn PHP from <font color='blue'>".tutorials."</font>"; // no $
sign for constants
}
test();
?>
</body>
</html>
14
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
PHP Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform
common arithmetical operations, such as addition, subtraction,
multiplication etc.
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
Result of raising $x to the $y'th
** Exponentiation $x ** $y
power (Introduced in PHP 5.6)
15
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
PHP Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's value.
Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
Example:
<html>
<head><title>Logical Operators</title><head>
16
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
<body>
<?php
$x=10;
$y=5;
?>
</body>
</html>
Output:
Arithmetic Operators
Add = 10+5 = 15
17
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
Sub = 10-5 = 5
Mul = 10*5 = 50
Div = 10/5 = 2
Assignment Operators
Add = 15
Sub = 10
Mul = 50
Div = 10
Increment / Decrement Operators
Pre-Increment = 11
Post - Increment = 11
After Increment = 12
Relational Operators
bool(false) => 12<5
bool(true) => 12>5
bool(false) => 12<=5
bool(true) => 12>=5
bool(true) => 12!=5
Logical Operators
bool(true) => 12&&5
bool(true) => 12||5
bool(false) => 12 xor 5
1. CONDITIONAL STATEMENTS:
Conditional statements are used to perform different actions based on
different conditions.
Very often when you write code, you want to perform different actions for
different decisions. We can use conditional statements in our code to do
this.
In PHP we have the following conditional statements:
if statement - executes some code only if a specified condition is true
if...else statement - executes some code if a condition is true and another
code if the condition is false
if...elseif....else statement - specifies a new condition to test, if the first
condition is false
switch statement - selects one of many blocks of code to be executed
18
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
1. if Statement
The if statement is used to execute some code only if a specified condition is
true.
Syntax:
if (condition) {
code to be executed if condition is true;
}
Example:
<?php
Output:
$t = date("H");
Good Morning!
if ($t < "12") {
echo "Good Morning!";
}
?>
2. if...else Statement
Use the if....else statement to execute some code if a condition is true and
another code if the condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than
20, and "Have a good night!" otherwise:
<?php
$t = date("H");
Output:
19
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
3. if...elseif....else Statement
Use the if....elseif...else statement to specify a new condition to test, if the first
condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} elseif (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good morning!" if the current time is less
than 10, and "Have a good day!" if the current time is less than 20. Otherwise it
will output "Have a good night!”
<?php
$t = date("H");
echo "<p>The hour (of the server) is " . $t;
echo ", and will give the following message:</p>";
4. switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
20
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
How it works?
First we have a single expression n (most often a variable), that is
evaluated once.
The value of the expression is then compared with the values for each case
in the structure.
If there is a match, the block of code associated with that case is executed.
Use break to prevent the code from running into the next case
automatically.
The default statement is used if no match is found.
Example:
<?php
$favcolor = "red";
Output:
2. LOOPING STATEMENTS:
Looping statements are used to perform certain actions repeatedly when
the specified condition is true.
Loops:
Often when we write code, we want the same block of code to run over and
over again in a row. Instead of adding several almost equal code-lines in a
script, we can use loops to perform a task like this.
21
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
In PHP, we have the following looping statements:
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
1. while Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true) {
code to be executed;
}
The example below first sets a variable $x to 1 ($x = 1). Then, the while loop will
continue to run as long as $x is less than, or equal to 5 ($x <= 5). $x will
increase by 1 each time the loop runs ($x++):
Output:
<?php
$x = 1; The number is: 1
The number is: 2
while($x <= 5) { The number is: 3
echo "The number is: $x <br>"; The number is: 4
The number is: 5
$x++;
}
?>
2. do...while Loop
The do...while loop will always execute the block of code once, it will then check
the condition, and repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop
will write some output, and then increment the variable $x with 1. Then the
condition is checked (is $x less than, or equal to 5?), and the loop will continue
to run as long as $x is less than, or equal to 5:
<?php
$x = 1;
22
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming Output:
do {
echo "The number is: $x <br>"; The number is: 1
$x++; The number is: 2
The number is: 3
} while ($x <= 5);
The number is: 4
?>
The number is: 5
3. for Loop
PHP for loops execute a block of code a specified number of times.
The for loop is used when you know in advance how many times the script
should run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed;
}
Parameters:
o init counter: Initialize the loop counter value
o test counter: Evaluated for each loop iteration. If it evaluates to
TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
o increment counter: Increases the loop counter value
4. foreach Loop:
The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array.
Syntax
foreach ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to
$value and the array pointer is moved by one, until it reaches the last array
element.
The following example demonstrates a loop that will output the values of the
given array ($colors):
23
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
<?php Output:
$colors = array("red", "green", "blue", "yellow"); red
green
foreach ($colors as $value) { blue
echo "$value <br>"; yellow
}
?>
4.1.8: ARRAYS
An array is a data structure that stores one or more similar type of values
in a single value
There are three different kinds of arrays and each array value is accessed using
an ID which is called array index.
1) Numeric array - An array with a numeric index. Values are stored and
accessed in linear fashion.
2) Associative array - An array with strings as index. This stores element
values in association with key values rather than in a strict linear index
order.
3) Multidimensional array - An array containing one or more arrays and
values are accessed using multiple indices
CREATING ARRAYS:
In PHP, the array() function is used to create an array: array();
1. Numeric Array
These arrays can store numbers, strings and any object but their index will
be represented by numbers.
By default array index starts from zero.
Example
Following is the example showing how to create and access numeric arrays.
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
$i=0;
foreach( $numbers as $value )
{
echo "numbers[$i] = $value <br />";
24
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
$i++;
}
/* Second method to create array. */ Output:
$numbers[0] = "one"; numbers[0] = 1
$numbers[1] = "two"; numbers[1] = 2
$numbers[2] = "three"; numbers[2] = 3
$numbers[3] = "four"; numbers[3] = 4
$numbers[4] = "five"; numbers[4] = 5
numbers[0] = one
numbers[1] = two
$i=0;
numbers[2] = three
foreach( $numbers as $value ) numbers[3] = four
{ numbers[4] = five
echo "numbers[$i] = $value <br />";
$i++;
}
?>
</body>
</html>
2. Associative Arrays
The associative arrays are very similar to numeric arrays in term of
functionality but they are different in terms of their index.
Associative array will have their index as string so that you can establish a
strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array
would not be the best choice. Instead, we could use the employees names
as the keys in our associative array, and the value would be their
respective salary.
Example:
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array(
"AAA" => 2000,
"BBB" => 1000,
"CCC" => 500
);
25
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
3. Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an
array.
Each element in the sub-array can be an array, and so on.
Values in the multi-dimensional array are accessed using multiple index.
<html>
<body>
<?php
$marks = array(
"AAA" => array
( "physics" => 35,
"maths" => 30,
"chemistry" => 39 ),
26
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
</body>
</html>
Output:
4.1.9: FUNCTIONS
Definition: A function is a piece of code which takes one or more input in the
form of parameter and does some processing and returns a value.
Creating functions:
Example:
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
27
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
<?php
function addFunction($num1, $num2) // function definition
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
</body>
</html>
Output:
Sum of the two numbers is : 30
function addSix(&$num)
{
$num += 6;
}
$orignum = 10;
addFive( $orignum );
28
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
</body>
</html>
29
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
This will display following result –
Returned value from the function : 30
<!DOCTYPE html>
<html>
<body>
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // this function call will use the default value „50‟
setHeight(135);
setHeight(80);
?>
</body>
</html>
Output:
The height is : 350
The height is : 50
The height is : 135
The height is : 80
30
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
1. Array Functions:
These functions allow you to interact with and manipulate arrays in various
ways. Arrays are essential for storing, managing, and operating on sets of
variables.
Function Description
array() Create an array
array_chunk() Splits an array into chunks of arrays
array_combine() Creates an array by using one array for keys and
another for its values
array_count_values() Returns an array with the number of occurrences for
each value
array_key_exists() Checks if the specified key exists in the array
array_keys() Returns all the keys of an array
array_merge() Merges one or more arrays into one array
array_pop() Deletes the last element of an array
array_product() Calculates the product of the values in an array
array_push() Inserts one or more elements to the end of an array
array_rand() Returns one or more random keys from an array
array_reverse() Returns an array in the reverse order
array_search() Searches an array for a given value and returns the key
array_shift() Removes the first element from an array, and returns the
value of the removed element
array_slice() Returns selected parts of an array
array_splice() Removes and replaces specified elements of an array
array_sum() Returns the sum of the values in an array
sort() Sorts an array
<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);
echo "Comibination of Two Arrays : ";
print_r($c);
$c = array('avocado','watermelon','banana');
echo "<br>";
echo "Difference of Two Arrays : ";
print_r(array_diff($b,$c));
$d = array(10,4,2,7,1);
echo "<br>Sum of array = ";
print_r(array_sum($d));
31
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
echo "<br>product of array = ";
print_r(array_product($d));
Output:
Comibination of Two Arrays :
Array ( [green] => avocado [red] => apple [yellow] => banana )
Difference of Two Arrays : Array ( [1] => apple )
Sum of array = 24
product of array = 560
Sorting of array = Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 7 [4] => 10 )
2. Class/Object Functions
These functions allow you to obtain information about classes and instance
objects.
You can obtain the name of the class to which an object belongs, as well as
its member properties and methods.
Function Description
class_exists() Checks if the class has been defined
get_class_methods() Gets the class methods' names
get_class_vars() Get the default properties of the class
get_class() Returns the name of the class of an object
get_object_vars() Gets the properties of the given object
get_parent_class() Retrieves the parent class name for object or class
is_a() Checks if the object is of this class or has this class
as one of its parents
method_exists() Checks if the class method exists
property_exists() Checks if the object or class has a property
Example:
<?php
class Box {
var $l = 10;
var $b = 20;
function volume()
{
$vol=$l*$b;
32
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
}
}
Output:
Variables in the class
l : 10
b : 20
Methods in the class
volume
3. Date Functions
These functions allow you to get the date and time from the server where your
PHP scripts are running.
Function Description
date_modify() Alters the timestamp
date_sunrise() Returns the time of sunrise for a given day / location
date_sunset() Returns the time of sunset for a given day / location
date_timezone_set() Sets the time zone for the DateTime object
date() Formats a local time/date
getdate() Returns an array that contains date and time information
for a Unix timestamp
gettimeofday() Returns an array that contains current time information
gmdate() Formats a GMT/UTC date/time
localtime() Returns an array that contains the time components of a
Unix timestamp
time() Returns the current time as a Unix timestamp
33
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
Example:
<?php
print date('r');
print "<br>";
print date('D, d M Y H:i:s T');
print "<br>";
?>
Output:
Thu, 03 Sep 2015 10:42:58 +0000
Thu, 03 Sep 2015 10:42:58 UTC
4. String Functions
String functions are used to manipulate strings.
Function Description
chr returns a specific character
count_chars return information about characters used in string
echo output one or more strings
fprintf write a formatted string to a stream
str_pad pad a string to a certain length with another string
str_repeat repeat a string
str_replace replace all occurrences of the search string with the
replacement string
str_ireplace case-insensitive version str_replace
strlen get string length
strcmp string comparison
strncmp string comparison of the first n characters
strpos find the position of the first occurrence of a substring in a
string
Example:
<html>
<body>
<?php
$str1="Welcome php";
echo "length of 'Welcome php' = ".strlen($str1)."<br>";
$str2="welcome php";
echo "compare(Welcome pjp , welcome php) =
".strcmp($str1,$str2)."<br>";
</body>
</html>
Output:
Form: A Document that containing black fields, that the user can fill the data or
user can select the data.
What is Validation?
Validation means check the input submitted by the user.
There are two types of validation are available in PHP. They are as follows −
Client-Side Validation − Validation is performed on the client machine web
browsers.
Server Side Validation − After submitted by data, The data has sent to a
server and perform validation checks in server machine.
The PHP superglobals $_GET and $_POST are used to collect form-data.
35
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
Example:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = test_input($_POST["email"]);
$website = $_POST["website"];
$comment = $_POST["comment"];
$gender = $_POST["gender"];
}
36
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
function test_input($data) {
if(ereg("^[a-zA-Z0-9._-]+@[a-zA-Z0-9]+.[a-z.]{2,5}$",$data))
return "<script>alert('valid Email Id')</script>".$data;
else
return "false";
}
?>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
37
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
Output:
38
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
4.1.15: Connecting Database
39
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
40
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
41
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
42
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
43
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
4.2.1: Basics of XML
XML (eXtensible Markup Language) is a mark up language.
XML is a mark-up language that defines set of rules for encoding
documents in a format that is both human readable and machine
readable.
XML is designed to store and transport data.
Xml was released in late 90‟s. it was created to provide an easy to use and
store self-describing data.
XML became a W3C Recommendation on February 10, 1998.
XML is not a replacement for HTML.
XML is designed to be self-descriptive.
XML is designed to carry data, not to display data.
XML tags are not predefined. You must define your own tags.
XML is platform independent and language independent.
In this chapter, we will discuss the simple syntax rules to write an XML
document. Following is a complete XML document −
You can notice there are two kinds of information in the above example −
Markup, like <contact-info>
The text, or the character data, Tutorials Point and (040) 123-4567.
44
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
The following diagram depicts the syntax rules to write different types of markup
and text in an XML document.
XML Declaration
The XML document can optionally have an XML declaration. It is written as
follows −
<?xml version = "1.0" encoding = "UTF-8"?>
Where version is the XML version and encoding specifies the character encoding
used in the document.
Root Element − An XML document can have only one root element. For
example, following is not a correct XML document, because both
the x and y elements occur at the top level without a root element −
<x>...</x>
<y>...</y>
The Following example shows a correctly formed XML document −
<root>
<x>...</x>
<y>...</y>
</root>
XML Attributes
An attribute specifies a single property for the element, using a name/value
pair. An XML-element can have one or more attributes. For example −
<a href = "http://www.abc.com/">abc Tutorial!</a>
Here href is the attribute name and http://www.abc.com/ is attribute value.
46
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
Syntax Rules for XML Attributes
Attribute names in XML (unlike HTML) are case sensitive. That
is, HREF and href are considered two different XML attributes.
Same attribute cannot have two values in a syntax. The following example
shows incorrect syntax because the attribute b is specified twice
−
<a b = "x" c = "y" b = "z"> .... </a>
Attribute names are defined without quotation marks, whereas attribute
values must always appear in quotation marks. Following example
demonstrates incorrect xml syntax
−
<a b = x>. ....</a>
In the above syntax, the attribute value is not defined in quotation marks.
XML References
References usually allow you to add or include additional text or markup in an
XML document. References always begin with the symbol "&" which is a
reserved character and end with the symbol ";". XML has two types of references
−
Entity References − An entity reference contains a name between the
start and the end delimiters. For example & where amp is name.
The name refers to a predefined string of text and/or markup.
Character References − These contain references, such as A,
contains a hash mark (“#”) followed by a number. The number always
refers to the Unicode code of a character. In this case, 65 refers to
alphabet "A".
XML Text
The names of XML-elements and XML-attributes are case-sensitive, which
means the name of start and end elements need to be written in the same
case. To avoid character encoding problems, all XML files should be saved as
Unicode UTF-8 or UTF-16 files.
Whitespace characters like blanks, tabs and line-breaks between XML-
elements and between the XML-attributes will be ignored.
Some characters are reserved by the XML syntax itself. Hence, they cannot be
used directly. To use them, some replacement-entities are used, which are
listed below –
Not Allowed Character Replacement Entity Character Description
47
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
& & ampersand
48
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
6) XML Attribute values must always be quoted
XML elements can have attributes in name/value pairs just like in HTML.
In XML, the attribute values must always be quoted:
<note date="12/11/2007">
<to>Tove</to>
<from>Jani</from>
</note>
7) 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:
<message>salary < 1000</message>
To avoid this error, replace the "<" character with an entity reference:
<message>salary < 1000</message>
8) Comments in XML
The syntax for writing comments in XML is similar to that of HTML:
<!-- This is a comment -->
Two dashes in the middle of a comment are not allowed:
<!-- This is an invalid -- comment -->
Well Formed XML documents: XML documents that conform to the syntax
rules above are said to be "Well Formed" XML documents.
Valid XML Document:
If an XML document conforms to its DTD/Schema that defines the proper
structure of the document, then the XML document is valid XML document.
49
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
An XML document can reference a Document Type Definition (DTD) or a
schema that defines the proper structure of the XML document. When an XML
document references a DTD or a schema, XML parsers (called validating
parsers) can read the DTD/Schema and check that the XML document follows
the structure defined by the DTD/Schema. If the XML document conforms to the
DTD/schema, the XML document is valid.
XML HTML
Software and hardware independent Software and hardware dependent
To send and store data To display data
Focus on what data is present Focus on how data looks
It is a Framework for markup language
It is a markup language
definition
Case sensitive Case insensitive
Transport data between app and database Design client side web programs
Custom tags allowed Only predefined tags
Open and close tags are strict Not strict
White space insensitive White space insensitive
Carry information Display information
Dynamic Static
DTD stands for Document Type Definition. An XML DTD defines the
structure of an XML document.
XML DTD is used to define the basic building block of any XML
document. Using DTD, we can specify the various element types,
attributes, and their relationships with one another.
XML DTD is used to specify the set of rules for structuring data in any
XML file.
An XML document is considered “well formed” and “valid” if it is
successfully validated against DTD.
50
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
2. Attribute:- Used to specify the values of the element. It is to provide
additional information to an element.
3. CDATA:- Character Data. CDATA will be parsed by the parser.
4. PCDATA:- Parsed character data (ie. Text).
An example of DTD
DTD is declared inside<!DOCTYPE> definition when the DTD declaration is
internal. In this example we can see that there is an XML document that has a
<!DOCTYPE> definition. The bold part in the following example is the DTD
declaration.
<?xml version="1.0"?>
<!-- XML DTD declaration starts here -->
<!DOCTYPE beginnersbook [
<!ELEMENT beginnersbook (to,from,subject,message)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT subject (#PCDATA)>
<!ELEMENT message (#PCDATA)>
]>
<!-- XML DTD declaration ends here-->
<beginnersbook>
<to>My Readers</to>
<from>Chaitanya</from>
<subject>A Message to my readers</subject>
<message>Welcome to beginnersbook.com</message>
</beginnersbook>
Explanation:
!DOCTYPE beginnersbook defines that this is the beginning of the DTD declaration and the
51
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
52
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
Advantages of DTD
XML processor enforces structure, as defined in DTD
Application is accessed easily in document structure
DTD gives hint to XML processor
Reduces size of document
employee.xsd
1. <?xml version="1.0"?>
2. <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" >
3. <xs:element name="employee">
4. <xs:complexType>
5. <xs:sequence>
6. <xs:element name="firstname" type="xs:string"/>
7. <xs:element name="lastname" type="xs:string"/>
8. <xs:element name="email" type="xs:string"/>
9. </xs:sequence>
10. </xs:complexType>
11. </xs:element>
12. </xs:schema>
Let's see the xml file using XML schema or XSD file.
employee.xml
53
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
1. <?xml version="1.0"?>
2. <employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="employee.xsd">
3.
4. <firstname>James</firstname>
5. <lastname>Gosling</lastname>
6. <email>[email protected]</email>
7. </employee>
1. Simple Type –
A simple element is an XML element that can contain only text. It cannot
contain any other elements or attributes.
It contains less attributes, child elements and cannot be left empty.
Simple type element is used only in the context of the text.
The syntax for defining a simple element is:
<xs:element name="xxx" type="yyy"/>
Some of predefined simple types are: xs:integer, xs:boolean, xs:string,
xs:date.
For example:
<xs:element name="phone_number" type="xs:int" />
2. Complex Type –
A complex type is a container for other element definitions.
This allows you to specify which child elements an element can contain
and to provide some structure within your XML documents.
For example:
54
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
<xs:element name="Address">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="company" type="xs:string" />
<xs:element name="phone" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
3. Global Types –
With global type, you can define a single type in your document, which
can be used by all other references.
For example, suppose you want to generalize the person and company
for different addresses of the company. In such case, you can define a
general type as below:
<xs:element name="AddressType">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="company" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
55
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
Instead of having to define the name and the company twice (once for
Address1 and once for Address2), we now have a single definition.
This makes maintenance simpler, i.e., if you decide to add "Postcode"
elements to the address, you need to add them at just one place.
xs:string
xs:decimal
xs:integer
xs:boolean
xs:date
xs:time
i) <xs:string> data type
The <xs:string> data type can take characters, line feeds, carriage returns,
and tab characters.
The XML processor does not replace line feeds, carriage returns, and tab
characters in the content with space and keep them intact.
For example, multiple spaces or tabs are preserved during display.
Example
56
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
<lastname>Refsnes</lastname>
<age>36</age>
<dateborn>1970-03-27</dateborn>
57
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
58
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
4.2.6: XML Parsers and Validation
XML parser validates the document and check that the document is well
formatted.
59
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
The DOM approach is useful for The SAX approach is useful for
net Programming
smaller applications because it parsing the large XML document
is simpler to use but it is because it is event based, XML
4. certainly not used for larger gets parsed node by node and
XML documents because it will does not require large amount of
then require larger amount of memory
memory
5. We can insert or delete a node We can insert or delete a node
Traversing is done in any Top to bottom traversing is done
6.
direction in DOM approach in SAX approach
Example: Checking the Well Formedness of XML document using DOM API.
dom.java
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
User.xml
<?xml version="1.0"?>
<userdata>
<user1>
<userno>001</userno>
<username>Bala</username>
<phonenumner>123456789</phonenumber>
<address>Chennai</Chennai>
</user1>
<user2>
<userno>002</userno>
<username>Suresh</username>
<phonenumner>987654321</phonenumber>
<address>madurai</Chennai>
</user2>
<user3>
<userno>003</userno>
<username>arul</username>
<phonenumner>1122334455</phonenumber>
<address>Vellore</Chennai>
</user3>
</userdata>
61
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
Output:
C:> javac dom.java
C:> java dom
Enter file name dom.xml
dom.xml is well formed
62
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
Program Explanation:
63
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
Output:
Advantages
1) It supports both read and write operations and the API is very simple to use.
2) It is preferred when random access to widely separated parts of a document is
required.
Disadvantages
1) It is memory inefficient. (Consumes more memory because the whole XML
document needs to loaded into memory).
2) It is comparatively slower than other parsers.
Example: Checking the Well Formedness of XML document using SAX API.
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
public class Parsing_SAXDemo
{
public static void main(String bala[])
{
try
{
System.out.println(“Enter XML document name”);
BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
String filename = input.readLine();
File fp = new File(filename);
64
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
if(fp.exists())
{
try
{
XMLReader reader = XMLReaderFactory.CreateXMLReader();
reader.parse(filename);
System.out.println(“filename + “is well formed”);
}
catch(Exception e)
{
System.out.println(“filename + “is not well formed”);
System.exit(1);
}
}
else
{
System.out.println(“file not found”);
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
Output:
65
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
Advantages
1) It is simple and memory efficient.
2) It is very fast and works for huge documents.
Disadvantages
1) It is event-based so its API is less intuitive.
2) Clients never know the full information because the data is broken into pieces.
XSL document
XSL Elements:
Elements Description
<xsl:template> Contains rules to apply when a
specified node is matched. The
“match” attribute is associated with
this element. The match= “/” defines
the whole document.
<xsl:value-of select = “expression”> Selects the value of an XML element
and adds it to the output tree. The
select attribute contains an XPath
expression.
<xsl:for-each select = “expression”> Applies a template to every node
selected by the XPath expression.
<xsl:sort select = “expression”> Sorts the nodes selected by <<xsl:for-
67
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
each select = “expression”> element.
<xsl:output> Used to define the format of the output
document.
<xsl:copy> Adds the current node to the output
tree.
68
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
<address>chennai</address>
</student>
<student>
<name>EEE</name>
<reg_no>2002</reg_no>
<year>1</year>
<semester>II</semester>
<grade>C</grade>
<address>chennai</address>
</student>
</student-details>
Stud.xsl
69
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
</xsl:for-each>
</table>
<hr/>
<h1>First Year Students</h1>
<table border="1">
<tr bgcolor="white">
<th>Name</th>
<th>Register No</th>
<th>Year</th>
<th>Semester</th>
<th>Grade</th>
<th>Address</th>
</tr>
70
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
<td><xsl:value-of select="semester"/></td>
<td><xsl:value-of select="grade"/></td>
<td><xsl:value-of select="address"/></td>
</tr>
</xsl:for-each>
</table>
</center>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
OUTPUT:
71
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
PART A
<?php
echo "Hello World!";
?>
72
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter
</body>
EnggTree.com
net Programming
</html>
<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
18. What are the two sets of regular expressions offered by PHP?
PHP offers functions specific to two sets of regular expression functions:
POSIX extended Regular Expressions
PERL compatible Regular Expressions
The ereg() function searches a string specified by string for a string specified by pattern,
ereg()
returning true if the pattern is found, and false otherwise.
The ereg_replace() function searches for string specified by pattern and replaces pattern
ereg_replace()
with replacement if found.
The eregi() function searches throughout a string specified by pattern for a string
eregi()
specified by string. The search is not case sensitive.
The eregi_replace() function operates exactly like ereg_replace(), except that the search
eregi_replace()
for pattern in string is not case sensitive.
The split() function will divide a string into various elements, the boundaries of each
split()
element based on the occurrence of pattern in string.
The spliti() function operates exactly in the same manner as its sibling split(), except that
spliti()
it is not case sensitive.
75
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming The sql_regcase() function can be thought of as a utility function, converting each
sql_regcase() character in the input parameter string into a bracketed expression containing two
characters.
The preg_match() function searches string for pattern, returning true if pattern exists,
preg_match()
and false otherwise.
The preg_replace() function operates just like ereg_replace(), except that regular
preg_replace()
expressions can be used in the pattern and replacement input parameters.
The preg_split() function operates exactly like split(), except that regular expressions
preg_split()
are accepted as input parameters for pattern.
The preg_grep() function searches all elements of input_array, returning all elements
preg_grep()
matching the regexp pattern.
25. What do you mean by XML declaration? Give an example. (MAY/JUNE 2013)
The XML declaration is a processing instruction that identifies the document as being
XML. All XML documents should begin with an XML declaration.
For example,
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
26. What is meant by a XML namespace?(April / May 2011, 2014, Nov / Dec 2012,
2013,NOV/DEC 2016)
An XML namespace is a collection of element and attribute names. XML namespace provide a
means for document authors to unambiguously refer to elements with the same name (i.e., prevent
collisions).
Example:
<subject>Geometry</subject> // data for student from school
and
<subject>Cardiology</subject> // data for student from medicine
Both the markup uses the element “subject” to markup data. Namespace can differentiate these two
“subject” elements:
<highschool:subject>Geometry</highschool:subject>
and <medicalschool:subject>Cardiology</medicalschool:subject>
Example:
77
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter
<root>
EnggTree.com
net Programming
<highschool:subject xmlns:highschool="http://www.abcschool.edu/subjects">
Geometry
</highschool:subject>
<medicalschool:subject xmlns:medicalshool="http://www.rmc.org/subjects">
Cardiology
</medicalschool:subject>
</root>
Example DTD :
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget to complete the work !</body>
< </note>
78
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
<!DOCTYPE root-element [element-declarations]>
where root-element is the name of root element and element-declarations is where you declare the
elements.
Example
Following is a simple example of internal DTD:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE address [
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
]>
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>
79
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
33. Give the syntax to declare XML schema.
Syntax:
The common syntax to declare a schema in our XML document as follows:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
The structure of the node tree begins with the root element and spreads out to the child elements till the
lowest level.
The nodes in the node tree have a hierarchical relationship to each other.The terms parent, child, and
sibling are used to describe the relationships. Parent nodes have children. Children on the same level are
called siblings (brothers or sisters).
80
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
In a node tree, the top node is called the root
net Programming
Every node, except the root, has exactly one parent node
A node can have any number of children
A leaf is a node with no children
Siblings are nodes with the same parent
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE addresses SYSTEM "addresses.dtd">
<addresses>
<person idnum="0123">
<lastName>Doe</lastName>
<firstName>John</firstName>
<phone location="mobile">(201) 345-6789</phone>
<email>[email protected]</email>
<address>
<street>100 Main Street</street>
<city>Somewhere</city>
<state>New Jersey</state>
<zip>07670</zip>
</address>
</person>
</addresses>
The following tree of element nodes represents this document:
81
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
39. Explain the use of XML Parser. (APRIL/MAY 2022)
It checks for proper format of the XML document (Well Formed Document) and may also validate
the XML documents (Valid XML Document).
XML parser validates the document and check that the document is well formatted.
43. What are the two types of XML parsers? And differentiate them.(U/AN)
Two types of XML Parsers:
1. Non-Validating XML Parsers
2. Validating XML Parsers
Non-Validating XML Parsers Validating XML Parsers
A non-validating parser checks if a document A Validating parser checks the syntax, builds
follows the XML syntax rules. It builds a tree the tree structure, and compares the structure
structure from the tags used in XML document of the XML document with the structure
and return an error only when there is a specified in the DTD associated with the
problem with the syntax of the document. document.
Non validating parsers process a document Validating parsers are slower because, in
faster because they do not have to check every addition to checking whether an XML document
element against a DTD. In other words, these is well formed; validating parsers also check
parsers check whether an XML document whether the XML document adheres to the
adheres to the rules of well-formed document. rules in the DTD used by the XML document.
The Expat parser is an example of non- Microsoft MSXML parser is an example of a
validating parser. validating parser.
82
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter
44. Define XSL.
EnggTree.com
net Programming
The Extensible Style sheet Language (XSL) is an XML vocabulary that decides how an XML
document data should look on the web browser. XSL is group of three technoliges:
1. XSL Transformations (XSLT): is technology for transforming the structure of the XML document
data into another structure.
2. XML Path Language (XPath): is a string-based language of expressions which defines the syntax
and semantics for efficiently locating elements and attributes in XML documents.
3. XSL Formatting Objects (XSL-FO): It is a separate XML vocabulary for defining document style
properties of an XML document .(print-oriented)
83
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com
net Programming
50. Why is XSLT an important tool in development of web applications?
(MAY/JUNE 2016)
XSLT is the most important part of XSL.
XSLT is used to transform an XML document into another XML document, or another type of
document that is recognized by a browser, like HTML and XHTML. Normally XSLT does this
by transforming each XML element into an (X)HTML element.
With XSLT you can add/remove elements and attributes to or from the output file. You can also
rearrange 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.
51. When should the super global arrays in PHP be used? Which super global array in PHP would
contain a HTML form's POST data? (MAY/JUNE 2016)
PHP super global variable is used to access global variables from anywhere in the PHP script.
There are two different types of form validation – Client side validation and Server side validations.
PART – B
1. Discuss in detail about how to create and use variables in PHP with example program.
2. What are the different data types available in PHP? Explain about converting between
different data types with example program.
3. Write a PHP program using arithmetic operator.
4. Explain the features of built-in functions in PHP with examples. (APRIL/MAY 2022)
5. Write a PHP program to do string manipulation. (NOV / DEC 2015)
6. Explain how user-defined functions are created in PHP.
7. Explain how input from an XHTML form is received in a PHP program.
8. How will you connect a PHP program with database? Explain with example application.
9. Explain how cookies are handled in PHP.
10. Explain in detail about using Regular Expressions in PHP.
11. Explain XML DTD. (APRIL/MAY 2022)
12. What are different types of DTD? Explain the same with example.
13. Explain the role of XML name spaces with examples. (MAY/JUNE 2012)
14. What is XML Schema? Explain how to create and use XML Schema document.
84
Downloaded from EnggTree.com
CCS375- Web Technologies Unit – 4 V Sem CSE
ttttTechnologiesTTYTTTechnologiesnter EnggTree.com (NOV/DEC 2015)
net Programming
15. Explain how a XML document can be displayed on a browser. (APRIL/MAY 2011)
16. Explain Document Tree with an example. (MAY/JUNE 2011, MAY/JUNE 2012)
17. Explain in detail about XSL. (NOV/ EC 2013)
18. Give an XSLT document and a source XML document explain the XSLT transformation
process that produces a single result XML document. (NOV/DEC 2012)
19. Explain in detail about XML parsers and validation. (NOV/DEC 2015, MAY/JUNE 2016)
20. Create a webserver based chat application using PHP. The application should provide the function
functions.
Login
Send message (to one or more contacts)
Receive messages(from one or more contacts)
Add/delete /modify contact list of the user
21. Discuss the application’s user interface and use comments in PHP to explain the code clearly.
(MAY/JUNE 2016)
22. List at least five significant differences between DID and XML schema for defining XML
document structures with appropriate examples. (MAY/JUNE 2016)
23. Explain the string comparison capability of PHP using regular expressions with an
example. (NOV/DEC2016)
24. Explain the steps in connecting a PHP code to a database. (NOV/DEC2016)
25. Explain in detail the XML schema, built in and user defined data type in detail.
(NOV/DEC2016)
26. Design simple calculator using PHP. (NOV/DEC2018)
27. Explain about the controls statements in PHP with example. (NOV/DEC 2018)
28. Design a PHP application for College Management System with appropriate built-in functions and
database. (NOV/DEC 2018)
29. What is spring framework ? What is use of it ? What are the advantages of Spring Framework?
(APRIL/MAY 2021)
30. Using XSLT, how would you extract a specific attribute from an element in an Xml document?
When constructing an XML DTD, how do you create an external entity reference in an attribute
value ? (APRIL/MAY 2021)
31. Write the HTML code for creating a feedback form as shown below. Include comments in code to
highlight the markup elements and their purpose. The HTML form should use POST for
submitting the form to a program ProcessContactForm.PHP. (MAY/JUNE 2016)
Internet Programming
35.Illustrate the steps and procedure to connect the PHP to any database. write a program of your own
demonstrate (NOV-DEC 2022)
36.Write a program using PHP to check whether the input to a function calculating factorial is valid(>0) or
not(NOV-DEC 2022)
85
Downloaded from EnggTree.com
EnggTree.com
CCS375 - WEB TECHNOLOGIES PIT / CSE
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js
"></script>
The ng-model directive binds the value of HTML controls (input, select,
textarea) to application data.
The ng-bind directive binds application data to the HTML view.
ANGULAR JS EXAMPLE:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js
"></script>
<body>
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div>
</body>
</html>
OUTPUT:
Input something in the input box:
Name:
Example explained:
AngularJS starts automatically when the web page has loaded.
The ng-app directive tells AngularJS that the <div> element is the "owner" of
an AngularJS application.
The ng-model directive binds the value of the input field to the application
variable name.
The ng-bind directive binds the content of the <p> element to the application
variable name.
ANGULARJS APPLICATIONS
It is mainly used for creating single web page application.
What is MVC?
The Model-View-Controller (MVC) framework is an architectural/design
pattern that separates an application into three main logical
components Model, View, and Controller. Each architectural component is
built to handle specific development aspects of an application.
It isolates the business logic and presentation layer from each other. It was
traditionally used for desktop graphical user interfaces (GUIs).
Nowadays, MVC is one of the most frequently used industry-standard web
development frameworks to create scalable and extensible projects.
It is also used for designing mobile apps.
MVC was created by Trygve Reenskaug.
The main goal of this design pattern was to solve the problem of users
controlling a large and complex data set by splitting a large application into
specific sections that all have their own purpose.
Features of MVC :
It provides a clear separation of business logic, Ul logic, and input
logic.
It offers full control over your HTML and URLs which makes it easy
to design web application architecture.
It is a powerful URL-mapping component using which we can build
applications that have comprehensible and searchable URLs.
It supports Test Driven Development (TDD).
Components of MVC :
The MVC framework includes the following 3 components:
Controller
Model
View
Controller:
The controller is the component that enables the interconnection between the
views and the model so it acts as an intermediary. The controller doesn‟t have
to worry about handling data logic, it just tells the model what to do. It
processes all the business logic and incoming requests, manipulates data using
the Model component, and interact with the View to render the final output.
View:
The View component is used for all the UI logic of the application. It
generates a user interface for the user. Views are created by the data which is
collected by the model component but these data aren‟t taken directly but
through the controller. It only interacts with the controller.
Model:
The Model component corresponds to all the data-related logic that the user
works with. This can represent either the data that is being transferred between
the View and Controller components or any other business logic-related data.
It can add or retrieve data from the database. It responds to the controller‟s
request because the controller can‟t interact with the database by itself. The
model interacts with the database and gives the required data back to the
controller.
The model would query the database for the list of all students and then return
that list back to the controller. If the response back from the model was
successful, then the controller would ask the view associated with students to
return a presentation of the list of students. This view would take the list of
students from the controller and render the list into HTML that can be used by
the browser.
The controller would then take that presentation and returns it back to the user.
Thus ending the request. If earlier the model returned an error, the controller
would handle that error by asking the view that handles errors to render a
presentation for that particular error. That error presentation would then be
returned to the user instead of the student list presentation.
As we can see from the above example, the model handles all of the data. The
view handles all of the presentations and the controller just tells the model and
view of what to do. This is the basic architecture and working of the MVC
framework.
Advantages of MVC:
Codes are easy to maintain and they can be extended easily.
The MVC model component can be tested separately.
The components of MVC can be developed simultaneously.
It reduces complexity by dividing an application into three
units. Model, view, and controller.
It supports Test Driven Development (TDD).
It works well for Web apps that are supported by large teams of web
designers and developers.
This architecture helps to test components independently as all
classes and objects are independent of each other
Search Engine Optimization (SEO) Friendly.
Disadvantages of MVC:
It is difficult to read, change, test, and reuse this model
It is not suitable for building small applications.
The inefficiency of data access in view.
The framework navigation can be complex as it introduces new
layers of abstraction which requires users to adapt to the
decomposition criteria of MVC.
Increased complexity and Inefficiency of data
Rails
Zend Framework
Fuel PHP
Laravel
Symphony
MVC is generally used on applications that run on a single graphical
workstation. The division of logical components enables readability and
modularity as well as it makes it more comfortable for the testing part.
UNDERSTANDING NG ATTRIBUTES
AngularJS Directives
AngularJS facilitates you to extend HTML with new attributes. These attributes
are called directives. AngularJS directives are HTML attributes with
an ng prefix.
Directives are special attributes starting with ng- prefix. Following are the most
common directives:
o ng-app: This directive starts an AngularJS Application.
o ng-init: This directive initializes application data.
o ng-model: This directive
o ng-model: This directive defines the model that is variable to be used in
AngularJS.
o ng-repeat: This directive repeats html elements for each item in a
collection.
AngularJS Directives List
AnglarJS directives are used to add functionality to your application. You can
also add your own directives for your applications.
Directive Description
rows.
ng-app directive
ng-app directive defines the root element. It starts an AngularJS Application and
automatically initializes or bootstraps the application when web page containing
AngularJS Application is loaded. It is also used to load various AngularJS
modules in AngularJS Application.
SYNTAX
<div ng-app = ""> ... </div>
EXAMPLE:
<!DOCTYPE html>
<html>
<head>
<title>AngularJS App</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></scr
ipt>
</head>
<body>
<!-- The ng-app directive defines the root element of the AngularJS application
-->
<div ng-app="myApp">
<h1>Welcome to my AngularJS App!</h1>
<!-- Other AngularJS directives and content -->
</div>
<script>
// AngularJS module creation
var app = angular.module('myApp', []);
// Define controllers, services, etc., within this module
</script>
</body>
</html>
The HTML file includes the AngularJS library through a script tag.
Inside a <div> with the ng-app="myApp" attribute, you can place
AngularJS content and directives.
This example simply displays a welcoming header within the AngularJS
root element.
The script section defines an AngularJS module named 'myApp' with an
empty dependency array [].
ng-init directive
The ng-init directive evaluates the given expression. This expression can be
used to initialize variables, set up event listeners, or perform other tasks that
need to be done when the application starts.
SYNTAX:
EXAMPLE:
OUTPUT:
Hello World!
The ng-init directive has created an AngularJS variable, which you can use in
the application.
ng-model directive
The ng-model directive is a core Angular directive that binds input, select, and
textarea elements to application data.
It establishes a two-way data binding between the view (HTML) and the model
(TypeScript), ensuring that any changes made to the input field are reflected in
the corresponding data property and vice versa.
In following example, we've defined a model named "name".
SYNTAX:
The syntax for the ng-model directive is as follows:
<input type="text" ng-model="propertyName">
<select ng-model="propertyName">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
<textarea ng-model="propertyName">Initial Text</textarea>
EXAMPLE:
Consider a component with a property named userName:
TYPESCRIPT
export class MyComponent {
userName: string = '';
}
To bind an input field to this property, use the ng-model directive as follows:
HTML
<input type="text" ng-model="userName">
Any changes made to the input field will be reflected in the userName property,
and any changes to the userName property will be reflected in the input field.
ng-repeat directive
ng-repeat directive repeats html elements for each item in a collection. In
following example, we've iterated over array of countries.
SYNTAX:
<div ng-app="myApp">
<ul>
Example:
<!DOCTYPE html>
<html>
<head>
<title>AngularJS ng-repeat Example</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></scr
ipt>
</head>
<body>
<!-- The ng-app directive defines the root element of the AngularJS application
-->
<div ng-app="myApp">
<h2>Fruits List:</h2>
<ul>
<!-- Using ng-repeat to loop through items -->
<li ng-repeat="fruit in fruits">{{ fruit }}</li>
</ul>
</div>
<script>
// AngularJS module creation
var app = angular.module('myApp', []);
The HTML file includes the AngularJS library using a script tag.
Inside the AngularJS root element (ng-app="myApp"), there is an
unordered list (<ul>) containing list items (<li>).
ng-repeat="fruit in fruits" creates a loop that iterates through the fruits
array.
For each item in the fruits array, the {{ fruit }} expression displays the
item's value within an <li> element.
The AngularJS script defines an app module and a controller named
myController.
The controller sets the value of $scope.fruits to an array of fruit names.
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Directives</title>
</head>
<body>
<h1>Sample Application</h1>
<div ng-app = "" ng-init = "countries = [{locale:'en-IND',name:'India'}, {locale:'en-
PAK',name:'Pakistan'}, {locale:'en-AUS',name:'Australia'}]">
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
<p>Hello <span ng-bind = "name"></span>!</p>
<p>List of Countries with locale:</p>
<ol>
<li ng-repeat = "country in countries">
{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
</li>
</ol>
</div>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"
></script>
</body>
</html>
OUTPUT:
ANGULARJS EXPRESSIONS
In AngularJS, expressions are used to bind application data to HTML.
AngularJS resolves the expression, and return the result exactly where the
expression is written.
Expressions are written inside double braces {{expression}}.They can also be
written inside a directive:
ng-bind="expression".
AnularJS expressions are very similar to JavaScript expressions. They can
contain literals, operators, and variables. For example:
{{ 5 + 5 }} or {{ firstName + " " + lastName }}
AngularJS Expressions Example
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"><
/script>
<body>
<div ng-app>
<p>A simple expression example: {{ 5 + 5 }}</p>
</div>
</body>
</html>
OUTPUT:
Note: If you remove the directive "ng-app", HTML will display the expression
without solving it.
You can also write expressions wherever you want, AngularJS will resolve the
expression and return the result.
AngularJS Numbers
Example:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"><
/script>
<body>
<div ng-app="" ng-init="quantity=5;cost=5">
<p>Total in dollar: {{ quantity * cost }}</p>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"><
/script>
<body>
<div ng-app="" ng-init="quantity=5;cost=5">
<p>Total in dollar: <span ng-bind="quantity * cost"></span></p>
</div>
</body>
</html>
OUTPUT:
Total in dollar: 25
AngularJS Strings
EXAMPLE
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"><
/script>
<body>
<div ng-app="" ng-init="firstName='Sonoo';lastName='Jaiswal'">
<p>My full name is: {{ firstName + " " + lastName }}</p>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"><
/script>
<body>
<div ng-app="" ng-init="firstName='Sonoo';lastName='Jaiswal'">
<p>My full name is: <span ng-bind="firstName + ' ' + lastName"></span></p>
</div>
</body>
</html>
OUTPUT:
My full name is: Sonoo Jaiswal
AngularJS Objects
EXAMPLE
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"><
/script>
<body>
<div ng-app="" ng-init="person={firstName:'Sonoo',lastName:'Jaiswal'}">
<p>The name is {{ person.firstName }}</p>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"><
/script>
<body>
<div ng-app="" ng-init="person={firstName:'Sonoo',lastName:'Jaiswal'}">
<p>The name is <span ng-bind="person.firstName"></span></p>
</div>
</body>
</html>
OUTPUT:
The name is: Sonoo Jaiswal
AngularJS Arrays
"AngularJS Arrays" involve handling and manipulating collections of data
organized in an array format within AngularJS applications. This includes using
features like data binding, controllers, directives, and filters to manage array
elements efficiently. AngularJS facilitates displaying array elements in the
view, performing operations like iteration, filtering, sorting, adding, removing,
and updating array items, thereby enabling seamless interaction with array-
based data structures in web applications.
EXAMPLE
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"><
/script>
<body>
<div ng-app="" ng-init="points=[1,15,19,2,40]">
<p>The first result is {{ points[0] }}</p>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"><
/script>
<body>
<div ng-app="" ng-init="points=[1,15,19,2,40]">
<p>The first result is <span ng-bind="points[0]"></span></p>
</div>
</body>
</html>
OUTPUT:
The first result is 1
ANGULARJS DATA BINDING
The one-way data binding is an approach where a value is taken from the data
model and inserted into an HTML element. There is no way to update model
from view. It is used in classical template systems. These systems bind data in
only one direction.
Data binding lets you treat the model as the single-source-of-truth in your
application. The view is a projection of the model at all times. If the model is
EXAMPLE PROGRAM:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"><
/script>
<body>
<div ng-app="" ng-init="firstName='Ajeet'">
<p>Input something in the input box:</p>
<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>
</div>
</body>
</html>
OUTPUT:
In the above example, the {{ firstName }} expression is an AngularJS data binding
expression. Data binding in AngularJS binds AngularJS expressions with
AngularJS data.
Let's take another example where two text fields are bound together with two
ng-model directives:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"><
/script>
<body>
<div data-ng-app="" data-ng-init="quantity=1;price=20">
<h2>Cost Calculator</h2>
Quantity: <input type="number" ng-model="quantity">
Price: <input type="number" ng-model="price">
<p><b>Total in rupees:</b> {{quantity * price}}</p>
</div>
</body>
</html>
OUTPUT:
ng-if Directive:
SYNTAX:
Conditions like ng-if else and ng-if else then are sub parts of ng-if .
EXAMPLE:
<h1>ngIf </h1>
<p *ngIf="showMe">
ShowMe is checked
</p>
<p *ngIf="!showMe">
ShowMe is unchecked
</p>
<h1>ngIf Else</h1>
<p *ngIf="showMe; else elseBlock1">
ShowMe is checked
</p>
OUTPUT:
ng-show:
ng-hide:
Used to hide an element based on a boolean expression.(or)
Conditionally hides an HTML element based on the truthiness of an
expression.
The ng-hide directive in AngularJS is a function using which an element
will be hidden if the expression is TRUE. If the Expression is FALSE, the
element will be shown. In the background, the element is shown or
hidden by removing or adding the .ng-hide CSS class onto the element
SYNTAX:
<div ng-show="condition">Content to show if condition is true</div>
<div ng-hide="condition">Content to hide if condition is true</div>
Example: ng-show
<h1> Guru99 Global Event</h1>
<div ng-app="DemoApp" ng-controller="DemoController">
<input type="button" value="Show Angular" ng-click="ShowHide()"/>
<br><br><div ng-show = "IsVisible">Angular</div>
</div>
<script type="text/javascript">
var app = angular.module('DemoApp',[]);
app.controller('DemoController',function($scope){
$scope.IsVisible = false;
$scope.ShowHide = function(){
$scope.IsVisible = true;
}
});
OUTPUT:
Example: ng-hide
<h1> Guru99 Global Event</h1>
<div ng-app="DemoApp" ng-controller="DemoController">
<input type="button" value="Hide Angular" ng-click="ShowHide()"/>
<br><br><div ng-hide="IsVisible">Angular</div>
</div>
<script type="text/javascript">
var app = angular.module('DemoApp',[]);
app.controller('DemoController',function($scope){
$scope.IsVisible = false;
$scope.ShowHide = function(){
$scope.IsVisible = $scope.IsVisible = true;
} });
</script>
OUTPUT:
ng-switch Directive:
Used to conditionally render content based on multiple conditions.
ng-switch, provide a way to dynamically control the visibility and rendering of
elements based on certain conditions. These directives enhance the flexibility
and responsiveness of AngularJS applications.
Angular evaluates the switch_expression at runtime and based on its
value displays or removes the elements from the DOM.
SYNTAX:
<div ng-switch="variable">
<div ng-switch-when="value1">Content for value1</div>
<div ng-switch-default>Default content</div>
</div>
EXAMPLE:
<div class='card'>
<div class='card-header'>
ngSwitch Example
</div>
<div class="card-body">
Input string : <input type='text' [(ngModel)]="num" />
<div [ngSwitch]="num">
<div *ngSwitchCase="'1'">One</div>
<div *ngSwitchCase="'2'">Two</div>
<div *ngSwitchCase="'3'">Three</div>
<div *ngSwitchCase="'4'">Four</div>
<div *ngSwitchCase="'5'">Five</div>
<div *ngSwitchDefault>This is Default</div>
</div>
</div>
</div>
OUTPUT:
STYLE DIRECTIVES
Style directives in AngularJS are a way of applying CSS styles to
HTML elements dynamically, based on some conditions or expressions.
They can be useful for creating responsive and interactive web pages that
change their appearance according to the user‟s actions or data changes.
TYPES:
There are two main types of style directives in AngularJS:
ng-style and
ng-class.
Other types of Style directives in AngularJS includes:
ng-blur
ng-click and
ng-disabled
PURPOSE:
The ng-style directive allows you to specify the style attribute for an HTML
element as an object or an expression returning an object. The object consists of
CSS properties and values, in key-value pairs.
ng-style directive:
The ng-style directive specifies the style attribute for the HTML element.
The value of the ng-style attribute must be an object, or an expression returning
an object.
The object consists of CSS properties and values, in key value pairs.
The ng-style Directive in AngularJS is used to apply custom CSS styles on an
HTML element. The expression inside the ng-style directive must be an
object. It is supported by all the HTML elements.
SYNTAX:
<element ng-style="expression"></element>
expression: It specifies the particular style to be implemented for the
respective element.
This is supported by all HTML elements.
Example program:
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></sc
ript>
<body ng-app="myApp" ng-controller="myCtrl">
<h1 ng-style="myObj">Welcome</h1>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.myObj = {
"color" : "white",
"background-color" : "coral",
"font-size" : "60px",
"padding" : "50px"
}
});
</script>
</body>
</html>
OUTPUT:
that is defined in the script (AngularJS) tag to apply background color to the h1
element i.e, WELCOME.
ng-class directive:
The ng-class directive dynamically binds one or more CSS classes to an
HTML element.
The value of the ng-class directive can be a string, an object, or an array.
If it is a string, it should contain one or more, space-separated class
names.
As an object, it should contain key-value pairs, where the key is the class
name of the class you want to add, and the value is a boolean value. The
class will only be added if the value is set to true.
As an array, it can be a combination of both. Each array element can be
either a string, or an object, described as above.
SYNTAX:
<element ng-class="expression"></element>
Example program:
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></scr
ipt>
<style>
.sky {
color:white;
background-color:lightblue;
padding:20px;
font-family:"Courier New";
}
.tomato {
background-color:coral;
padding:40px;
font-family:Verdana;
}
</style>
<body ng-app="">
<p>Choose a class:</p>
<select ng-model="home">
<option value="sky">Sky</option>
<option value="tomato">Tomato</option>
</select>
<div ng-class="home">
<h1>Welcome Home!</h1>
<p>I like it!</p>
</div>
</body>
</html>
OUTPUT:
Here we use the ng-class directive to choose between two options i.e., Sky and
Tomato within the same class “Home”.
There are two types of ng-class directive. They are:
ng-class-even
ng-class-odd
ng-class-even:
The ng-class-even Directive in AngularJS is used to specify the CSS classes
on every even appearance of HTML elements. It is used to dynamically bind
classes on every even HTML element. If the expression inside the ng-class-
even directive returns true then only the class is added else it is not added.
The ng-repeat directive is required for the ng-class-even directive to work. It
is supported by all HTML elements.
SYNTAX:
<element ng-class-even="expression">Contents...</element>
expression: This parameter returns more than one class name or simply
specifies the CSS class for even appearance of HTML elements.
Example program:
<table>
<tr ng-repeat="item in items" ng-class-even="'even'">
<td>{{ item }}</td>
</tr>
</table>
</div>
OUTPUT:
Here the class “even” is used to highlight the even items everytime a new item
is added by clicking “Add item” button.
ng-class-odd:
The ng-class-odd Directive in AngularJS is used to specify the CSS classes
on every odd appearance of HTML elements. It is used to dynamically bind
classes on every odd HTML element. If the expression inside the ng-class-odd
directive returns true then only the class is added else it is not added. The ng-
repeat directive is required for the ng-class-odd directive to work. This
directive can be utilized for the styling of the items in a list or rows in a table,
although, can be used for remaining HTML elements, as well. It is supported
by all HTML elements.
SYNTAX:
<element ng-class-odd="expression">Contents... </element>
Example program:
Here the class “odd” is used to highlight the odd items everytime a new item is
added by clicking “Add item” button.
ng-click directive:
The ng-click Directive in AngluarJS is used to apply custom behavior
when an element is clicked. It can be used to show/hide some element or
it can pop up an alert when the button is clicked.
In other words, The ng-click directive tells AngularJS what to do when an
HTML element is clicked.
SYNTAX:
<element ng-click="expression"></element>
Example program:
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></scr
ipt>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<p>Click the button to run a function:</p>
<button ng-click="myFunc()">OK</button>
<p>The button has been clicked {{count}} times.</p>
</div>
<script>
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.count = 0;
$scope.myFunc = function() {
$scope.count++;
};
}]);
</script>
</body>
</html>
OUTPUT:
ng-blur directive:
The ng-blur Directive in AngularJS is fired when an HTML element
loses their focus.
It doesn‟t override with element‟s original onblur event i.e. both the ng-
blur expression and original onblur event will execute.
SYNTAX:
<element ng-blur="expression">Contents... </element>
Example program:
<style>
.blurClass {background-color: lightgray;}
</style>
<script
src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script>
var module = angular.module('myApp', []);
module.controller('MyCtrl', function($scope) {});
</script>
OUTPUT
ANGULARJS CONTROLLERS
AngularJS controllers control the data of AngularJS applications.
AngularJS controllers are regular JavaScript Objects.
AngularJS applications are controlled by controllers.
The ng-controller directive defines the application controller.
A controller is a JavaScript Object, created by a standard
JavaScript object constructor.
Controller Methods:
A controller can have methods (variables as functions)
The example demonstrated a controller object with two properties: lastName
and firstName.
EXAMPLE:
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></scr
ipt>
<body>
<div ng-app="myApp" ng-controller="personCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
};
});
</script>
</body>
</html>
OUTPUT:
John
First Name:
Doe
Last Name:
personController.js
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
};
});
</script>
OUTPUT:
John
First Name:
Doe
Last Name:
AngularJS Scope:
The scope is the binding part between the HTML (view) and the
JavaScript (controller).
The scope is an object with the available properties and methods.
The scope is available for both the view and the controller.
When you make a controller in AngularJS, you pass the $scope object as
an argument
Root Scope:
All applications have a $rootScope which is the scope created on the
HTML element that contains the ng-app directive.
The rootScope is available in the entire application.
ANGULARJS FILTERS
Filters can be added in AngularJS to format data.
AngularJS provides filters to transform data:
currency Format a number to a currency format.
date Format a date to a specified format.
filter Select a subset of items from an array.
json Format an object to a JSON string.
OUTPUT:
The name is DOE
LOWERCASE:
->The lowercase filter format strings to lower case:
-> From the above example, instead of uppercase, you put lowercase.(inside the
<div> tag)
EXAMPLE:
<p>The name is {{ lastName | lowercase }}</p>
ORDERBY:
The orderBy filter sorts an array:
EXAMPLE:
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></scr
ipt>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<p>Looping with objects:</p>
<ul>
<li ng-repeat="x in names | orderBy:'country'">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England'},
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Mary',country:'England'},
{name:'Kai',country:'Norway'}
];
});
</script>
</body>
OUTPUT:
Looping with objects:
Joe, Denmark
Birgit, Denmark
Margareth, England
Mary, England
Jani, Norway
Hege, Norway
Kai, Norway
Carl, Sweden
Gustav, Sweden
CURRENCY:
The currency filter formats a number as currency:
EXAMPLE:
<div ng-app="myApp" ng-controller="costCtrl">
<h1>Price: {{ price | currency }}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('costCtrl', function($scope) {
$scope.price = 58;
});
</script>
<p>The currency filter formats a number to a currency format.</p>
OUTPUT:
Price: $58.00
The currency filter formats a number to a currency format.
FILTER:
The filter filter selects a subset of an array.
The filter filter can only be used on arrays, and it returns an array
containing only the matching items.
EXAMPLE
Return the names that contains the letter "i":
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names | filter : 'i'">
{{ x }}
</li>
</ul>
</div>
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Mary',country:'England'},
{name:'Kai',country:'Norway'}
];
$scope.orderByMe = function(x) {
$scope.myOrderBy = x;
}
});
</script>
</body>
</html>
OUTPUT:
ANGULARJS ROUTING
The ng-Route module helps your application to become a Single Page
Application.
What is Routing in AngularJS?
If you want to navigate to different pages in your application, but you
also want the application to be a SPA (Single Page Application), with no
page reloading, you can use the ng-Route module.
The ng-Route module routes your application to different pages without
reloading the entire application.
EXAMPLE:
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></scr
ipt>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-
route.js"></script>
<body ng-app="myApp">
<p><a href="#/!">Main</a></p>
<a href="#!red">Red</a>
<a href="#!green">Green</a>
<a href="#!blue">Blue</a>
<div ng-view></div>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.htm"
})
.when("/red", {
templateUrl : "red.htm"
})
.when("/green", {
templateUrl : "green.htm"
})
.when("/blue", {
templateUrl : "blue.htm"
});
});
</script>
<p>Click on the links to navigate to "red.htm", "green.htm", "blue.htm", or back
to "main.htm"</p>
</body>
</html>
OUTPUT:
Main
Red
Green
Blue
Main
Click on the links to navigate to "red.htm", "green.htm", "blue.htm", or back to
"main.htm"
What does we Need?
To make the applications ready for routing, we must include the
AngularJS Route module:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-
route.js"></script>
Then we must add the ngRoute as a dependency in the application
module:
var app = angular.module("myApp", ["ngRoute"]);
Now the application has access to the route module, which provides
the $routeProvider. Use the $routeProvider to configure different routes
in the application:
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.htm"
})
.when("/red", {
templateUrl : "red.htm"
})
.when("/green", {
templateUrl : "green.htm"
})
.when("/blue", {
templateUrl : "blue.htm"
});
});
$routeProvider
With the $routeProvider you can define what page to display when a user clicks
a link.
EXAMPLE:
Define a $routerProvider:
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></scr
ipt>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-
route.js"></script>
<body ng-app="myApp">
<p><a href="#/!">Main</a></p>
<a href="#!london">City 1</a>
<a href="#!paris">City 2</a>
<p>Click on the links to read about London and Paris.</p>
<div ng-view></div>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.htm"
})
.when("/london", {
templateUrl : "london.htm"
})
.when("/paris", {
templateUrl : "paris.htm"
});
});
</script>
</body>
</html>
OUTPUT:
Main
City 1
City 2
Click on the links to read about London and Paris.
Main
->Define the $routeProvider using the config method of your application. Work
registered in the config method will be performed when the application is
loading.
Controllers
With the $routeProvider you can also define a controller for each "view".
EXAMPLE:
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></scr
ipt>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-
route.js"></script>
<body ng-app="myApp">
<p><a href="#/!">Main</a></p>
<a href="#!london">City 1</a>
<a href="#!paris">City 2</a>
<p>Click on the links.</p>
<p>Note that each "view" has its own controller which each gives the "msg"
variable a value.</p>
<div ng-view></div>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.htm",
})
.when("/london", {
templateUrl : "london.htm",
controller : "londonCtrl"
})
.when("/paris", {
templateUrl : "paris.htm",
controller : "parisCtrl"
});
});
app.controller("londonCtrl", function ($scope) {
$scope.msg = "I love London";
});
app.controller("parisCtrl", function ($scope) {
$scope.msg = "I love Paris";
});
</script>
</body>
</html>
OUTPUT:
Main
City 1
City 2
Click on the links.
Note that each "view" has its own controller which each gives the "msg"
variable a value.
Main
The otherwise method
OUTPUT:
Main
Banana
Tomato
Click on the links to change the content.
Use the "otherwise" method to define what to display when none of the links are
clicked.
Nothing has been selected
MODULES
An AngularJS module defines an application.
The module is a container for the different parts of an application.
The module is a container for the application controllers.
Controllers always belong to a module.
Creating a Module:
A module is created by using the AngularJS function angular.module
The "myApp" parameter refers to an HTML element in which the
application will run.
Now you can add controllers, directives, filters, and more, to your
AngularJS application.
EXAMPLE:
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></scr
ipt>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
</body>
</html>
OUTPUT:
John Doe
ANGULAR FORMS
Forms are collection of controls that is input field , buttons , checkbox and
these can be validated real time . Forms in AngularJS provides data-binding and
validation of input controls. As soon as a user of the form completes writing a
field and moves to the next one it get validated and suggests the user where he
might have gone wrong .
Data-Binding
Input field :
SYNTAX :
<input type="text" ng-model="firstname">
<form>
<input id="myVar" type="checkbox" ngModel name="myVar"
#myVar="ngModel">
<p>The checkbox is selected: {{myVar.value}}</p>
<br />
<select ngModel name="mychoice" #myChoice="ngModel">
<option>A</option>
<option>E</option>
<option>I</option>
<option>O</option>
<option>U</option>
</select>
<p>The selected option from Dropdown {{ myChoice.value }}</p>
</form>
OUTPUT :
Radio buttons used in the forms should allow only one field
to be selected at a time to make sure this is the case we should associate it with
only ngModel .
EXAMPLE :
<form>
<p>Select a radio button to know which Vowel it is associated to:</p>
<input value="A" type="radio" ngModel name="myVar"
#myVar="ngModel">
<input value="E" type="radio" ngModel name="myVar"
#myVar="ngModel">
<input value="I" type="radio" ngModel name="myVar"
#myVar="ngModel">
OUTPUT :
<form>
<div class="form-group">
<label for="firstName">Name</label>
<input type="text"
id="firstName"
placeholder="Name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input
type="text"
id="email"
placeholder="Email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input
type="password"
id="password"
placeholder="Password">
</div>
<div class="form-group">
<label for="phone">mobile</label>
<input
type="text"
id="phone"
ngModel name="phone"
#phone="ngModel"
placeholder="Mobile">
</div>
</form>
<p>{{ phone.value }}</p>
OUTPUT :
FORM VALIDATION :
These all are the properties of the input field which can be either true or false.
Forms have the following states:
$pristine: It represents that the fields have not been modified yet.
$dirty: It illustrates that one or more fields have been modified.
$invalid: It specifies that the form content is not valid.
$valid: It specifies that the form content is valid.
$submitted: It specifies that the form is submitted.
These all are the properties of the form which can be either true or false. These
states can be used to show meaningful messages to the user.
EXAMPLE :
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></scr
ipt>
<body ng-app="">
<p>Try writing in the input field:</p>
<form name="myForm">
<input name="myInput" ng-model="myInput" required>
</form>
<p>The input's valid state is:</p>
<h1>{{myForm.myInput.$valid}}</h1>
</body>
</html>
OUTPUT :
WEB SERVICES
DEFINITION:
Web services are XML-based information exchange systems that use the
Internet for direct application-to-application interaction. These systems can
include programs, objects, messages, or documents. A web service is a
collection of open protocols and standards used for exchanging data between
applications or systems.
The Internet is the worldwide connectivity of hundreds of thousands of
computers of various types that belong to multiple networks. On the World
Wide Web, a web service is a standardized method for propagating messages
between client and server applications. A web service is a software module
that is intended to carry out a specific set of functions. Web services in cloud
computing can be found and invoked over the network.
The web service would be able to deliver functionality to the client that
invoked the web service.
A web service is a set of open protocols and standards that allow data to be
exchanged between different applications or systems. Web services can be
used by software programs written in a variety of programming languages and
running on a variety of platforms to exchange data via computer networks
such as the Internet in a similar way to inter-process communication on a
single computer.
Any software, application, or cloud technology that uses standardized web
protocols (HTTP or HTTPS) to connect, interoperate, and exchange data
messages – commonly XML (Extensible Markup Language) – across the
internet is considered a web service.
Web services have the advantage of allowing programs developed in different
languages to connect with one another by exchanging data over a web service
between clients and servers. A client invokes a web service by submitting an
XML request, which the service responds with an XML response.
just like a telephone directory has the name, address, and phone number of a
certain individual. So that a client application may figure out where it is.
The diagram depicts a very simplified version of how a web service would
function. The client would use requests to send a sequence of web service calls
to a server that would host the actual web service.
Remote procedure calls are what are used to make these requests. Calls to
methods hosted by the relevant web service are known as Remote Procedure
Calls (RPC). Example: Flipkart offers a web service that displays prices for
items offered on Flipkart.com. The front end or presentation layer can be
written in .Net or Java, but the web service can be communicated using either
programming language. The data that is exchanged between the client and the
server, which is XML, is the most important part of a web service design.
XML (Extensible markup language) is a simple intermediate language that is
understood by various programming languages. It is a counterpart to HTML.
As a result, when programs communicate with one another, they do so using
XML. This creates a common platform for applications written in different
programming languages to communicate with one another.
For transmitting XML data between applications, web services employ SOAP
(Simple Object Access Protocol). The data is sent using standard HTTP. A
SOAP message is data that is sent from the web service to the application. An
XML document is all that is contained in a SOAP message. The client
application that calls the web service can be created in any programming
language because the content is written in XML.
(a) Business Functions can be exposed over the Internet: A web service is a
controlled code component that delivers functionality to client applications or
end-users. This capability can be accessed over the HTTP protocol, which
means it can be accessed from anywhere on the internet. Because all apps are
now accessible via the internet, Web services have become increasingly
valuable. Because all apps are now accessible via the internet, Web services
have become increasingly valuable. That is to say, the web service can be
located anywhere on the internet and provide the required functionality.
also make use of web services. A .NET application, for example, can
communicate with Java web administrations and vice versa. To make the
application stage and innovation self-contained, web administrations are used.
(c) Communication with Low Cost: Because web services employ the SOAP
over HTTP protocol, you can use your existing low-cost internet connection to
implement them. Web services can be developed using additional dependable
transport protocols, such as FTP, in addition to SOAP over HTTP.
WEB APPLICATION
DEFINITION:
A web-application is an application program that is usually stored on a remote
server, and users can access it through the use of Software known as web-
browser.
In general, a web application can contain online shops (or we can also say them
e-commerce shops), webmail's, calculators, social media platforms, etc. There is
also some kind of web application that usually requires a special kind of web
browser to access them. We cannot access those kinds of web applications by
using regular web- browsers. However, most of the web applications available
on the internet can be accessed using a standard web browser.
If we talk about the web application in general, a web application usually uses a
combination of the server-side scripts such as PHP, ASP, for handling the
information/ data storage and retrieval of the data.
Some of them also use the client-side scripts such as JavaScript, HTML to
represent the data/information in front of the users, and some of the web
applications are also using both server-side and client-side at the same time.
Apart from that web applications also allow its users to create documents, share
them, or share the data/ information. By using the web application, users can
collaborate on same projects by event when they are not available on the same
geographical location.
After knowing that what a web application is, there may be a question hitting in
mind that how it will work.
A web application are generally coded using the languages supported by almost
every web-browsers such as HTML, JavaScript because these are the languages
that rely on the web browsers to render the program executable.
Some of the web applications are entirely static due to which they not required
any processing on the server at all while, on the other hand, some web
applications are dynamic and require server-side processing.
To operate a web- application, we usually required a web server (or we can say
some space on the web-server for our programs/application's code) to manage
the clients' upcoming requests and required an application server.
The application server performs the task that requested by the clients, which
also may need a database to store the information sometimes. Application server
technologies range from ASP.NET, ASP, and ColdFusion to PHP and JSP.
A standard web application usually has short development cycles and can be
easily developed with a small team of developers. As we all know, most of the
currently available web applications on the internet are written using the
programming languages such as the HTML (or HyperText Markup
Language), CSS( or Cascading Style Sheets), and Javascript that are used in
creating front-end interface (Client-side programming).
1. In general, a user sends a request to the web-server using web browsers such
as Google Chrome, Microsoft Edge, Firefox, etc over the internet.
2. Then, the request is forwarded to the appropriate web application server by
the web-server.
3. Web application server performs the requested operations/ tasks
like processing the database, querying the databases; produces the result
of the requested data.
4. The obtained result is sent to the web-server by the web application server
along with the requested data/information or processed data.
5. The web server responds to the user with the requested or processed
data/information and provides the result to the user's screen .
o All the users are able to access the same version of the web application,
which eliminates all compatibility issues.
o It also reduces software piracy in subscription-based web applications, for
example, SAAS (or Software as a service).
o They also reduce the expense for end-users, business owners because the
maintenance needed by the business is significantly less.
o Web applications are flexible. A user can work from any geographical
location as long as he has a working internet connection.
o It just takes a moment to create a new user by providing a username,
password, and URL, and it's all.
o After the availability of the cloud, storage space is now virtually
unlimited as long as you can afford it.
o A web application can be programmed to run on a wide variety of
operating systems, unlike native applications that can run on a particular
platform.
o Any standard web application is developed with some basic programming
languages like HTML, CSS that are compatible and well known among
the IT professionals.
FRAMEFORKS
DEFINITION:
Web Application Framework or simply “web framework” is a software
framework that is designed to support the development of web applications
including web services, web resources, and web APIs. Frameworks are, in
short, libraries that help you develop your application faster and smarter!
Nowadays, the number of Web Frameworks has increased greatly. To help you
pick up the most suitable one for your Web Application, we have compiled a
list of 10 best frameworks available online, in your preferred language.
1. Ruby on Rails
Ruby on Rails is an extremely productive web application framework written
by David Heinemeier Hansson. One can develop an application at least ten
times faster with Rails than a typical Java framework. Moreover, Rails
includes everything needed to create a database-driven web application, using
the Model-View-Controller pattern.
Websites using Ruby on Rails are GroupOn, UrbanDictionary, AirBnb,
Shopify, Github
2. Django
Django is another framework that helps in building quality web applications. It
was invented to meet fast-moving newsroom deadlines while satisfying the
tough requirements of experienced Web developers. Django developers say the
applications are ridiculously fast, secure, scalable, and versatile.
Websites using Django are Disqus, Pinterest, Instagram, Quora, etc.
4. ASP.NET
ASP.NET is a framework developed by Microsoft, which helps us to build
robust web applications for PC, as well as mobile devices. It is a high
performance and lightweight framework for building Web Applications using
.NET. All in all, a framework with Power, Productivity, and Speed.
Websites using ASP.NET are GettyImages, TacoBell, StackOverflow, etc.
5. METEOR
Meteor or MeteorJS is another framework that gives one a radically simpler
way to build realtime mobile and web apps. It allows for rapid prototyping and
produces cross-platform (Web, Android, iOS) code. Its cloud platform,
Galaxy, greatly simplifies deployment, scaling, and monitoring.
Websites using Meteor are HaggleMate, WishPool, Telescope, etc.
6. Laravel
Laravel is a framework created by Taylor Otwell in 2011 and like all other
modern frameworks, it also follows the MVC architectural pattern. Laravel
values Elegance, Simplicity, and Readability. One can right away start
learning and developing Laravel with Laracasts which has hundreds of
tutorials in it.
Websites using Laravel are Deltanet Travel, Neighbourhood Lender, etc.
7. Express
8. Spring
Spring, developed by Pivotal Software, is the most popular application
development framework for enterprise Java. Myriads of developers around the
globe use Spring to create high performance and robust Web apps. Spring
helps in creating simple, portable, fast, and flexible JVM-based systems and
applications.
Websites using spring are Mascus, Allocine, etc.
9. Play
Play is one of the modern web application framework written in Java and
Scala. It follows the MVC architecture and aims to optimize developer
productivity by using convention over configuration, hot code reloading, and
display of errors in the browser. Play quotes itself as “The High-Velocity Web
Framework”.
Websites using PLAY are LinkedIn, Coursera, LendUp, etc.
10. CodeIgniter
CodeIgniter, developed by EllisLab, is a famous web application framework
to build dynamic websites. It is loosely based on MVC architecture since
Controller classes are necessary but models and views are optional.
CodeIgnitor promises with exceptional performance, nearly zero-
configuration, and no large-scale monolithic libraries.
WEB TOOLS
DEFINITION:
HTML.
CSS.
AngularJS.
Bootstrap.
PHP.
NextJS.
TypeScript.
ExpressJS.
HTML:
It can be a stand-alone software dedicated to code writing and editing or a
part of an IDE (Integrated Development Environment). An HTML editor
provides more advanced features and is specifically designed for developers to
create web pages more efficiently. It ensures every string of code is clean and
works properly.
CSS:
Cascading Style Sheets (CSS) is a stylesheet language used to describe the
presentation of a document written in HTML or XML (including XML dialects
such as SVG, MathML or XHTML). CSS describes how elements should be
rendered on screen, on paper, in speech, or on other media.
ANGULARJS:
AngularJS starts automatically when the web page has loaded.The ng-
app directive tells AngularJS that the <div> element is the "owner" of an
AngularJS application.The ng-model directive binds the value of the input
field to the application variable name.The ng-bind directive binds the content
of the <p> element to the application variable name
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js
"></script>
<body>
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div>
</body>
</html>
BOOTSTRAP:
Bootstrap is a free, open source front-end development framework for the
creation of websites and web apps. Designed to enable responsive development
of mobile-first websites, Bootstrap provides a collection of syntax for template
designs.
PHP:
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.
<!DOCTYPE html>
<html>
<body>
<?php
echo "My first PHP script!";
?>
</body>
</html>
NEXTJS:
Next.js enables you to create full-stack Web applications by extending the latest
React features, and integrating powerful Rust-based JavaScript tooling for the
fastest builds.
Next.js is an open-source web development React-based framework created
by Vercel, which is famous for its unique features such as Server-side
rendering and enhanced SEO. It has some additional features such as data
fetching utilities, dynamic API routes, optimized builds, etc. It is a framework
built upon React, Webpack, and Babel.
TYPESCRIPT:
TypeScript allows specifying the types of data being passed around within the
code, and has the ability to report errors when the types don't match. For
example, TypeScript will report an error when passing a string into a function
that expects a number. JavaScript will not.
EXPRESSJS:
Express. js is the most popular backend framework for Node. js, and it is an
extensive part of the JavaScript ecosystem. It is designed to build single-page,
multi-page, and hybrid web applications, it has also become the standard for
developing backend applications with Node.
FIREBASE
Firebase is a product of Google which helps developers to build, manage, and
grow their apps easily. It helps developers to build their apps faster and in a
more secure way. No programming is required on the firebase side which makes
it easy to use its features more efficiently. It provides services to android, iOS,
web, and unity. It provides cloud storage. It uses NoSQL for the database for
the storage of data.
Firebase initially was an online chat service provider to various websites
through API and ran with the name Envolve. It got popular as developers used
it to exchange application data like a game state in real time across their users
more than the chats. This resulted in the separation of the Envolve architecture
and its chat system.
Features of Firebase:
This feature mainly includes backend services that help developers to build and
manage their applications in a better way. Services included under this feature
are:
scale. It stores data in the form of objects also known as Documents. It has a
key-value pair and can store all kinds of data like, strings, binary data, and even
JSON trees.
Here majorly all the application performance and testing features are provided.
All the features required to check and manage before launching your application
officially are provided in this section. Services included are:
Crashlytics: It is used to get real-time crash reports. These reports can further
be used to improve the quality of the application. The most interesting part of
this service is that it gives a detailed description of the crash which is easier to
analyse for the developers.
Performance monitoring: This service gives an insight to the performance
characteristics of the applications. The performance monitoring SDK can be
used to receive performance data from the application, review them, and make
changes to the application accordingly through the Firebase console.
Test lab: This service helps to test your applications on real and virtual devices
provided by Google which are hosted on the Google Datacentres. It is a cloud-
based app-testing infrastructure which supports testing the application on a wide
variety of devices and device configurations
App Distribution: This service is used to pre-release applications that can be
tested by trusted testers. It comes in handy as decreases the time required to
receive feedback from the testers.
Below listed are the advantages and disadvantages of using a Firebase backend:
Pros:
Free plans for beginners.
Real-time database is available.
Growing Community.
Images from the Docker Hub anytime or anywhere via the internet. It provides
features such as you can push your images as private or public. Mainly
DevOps team uses the Docker Hub. It is an open-source tool and freely
available for all operating systems. It is like storage where we store the images
and pull the images when it is required. When a person wants to push/pull
images from the Docker Hub they must have a basic knowledge of Docker.
Let us discuss the requirements of the Docker tool.
Docker Commands
There is “n” no. of commands in docker following are some of the commands
mostly used.
1. Docker Run
2. Docker Pull
3. Docker PS
4. Docker Stop
5. Docker Start
6. Docker rm
7. Docker RMI
8. Docker Images
9. Docker exec
10.Docker Login
Docker Engine
The software that hosts the containers is named Docker Engine. Docker
Engine is a client-server-based application. The docker engine has 3 main
components:
1. Server: It is responsible for creating and managing Docker images,
containers, networks, and volumes on the Docker. It is referred to as
a daemon process.
2. REST API: It specifies how the applications can interact with the
Server and instructs it what to do.
3. Client: The Client is a docker command-line interface (CLI), that
allows us to interact with Docker using the docker commands.
NODE JS
Node.js is an open-source server-side runtime environment built on
Chrome‟s V8 JavaScript engine.
It provides an event driven ,non-blocking (synchronous)I/O and cross-
platform run time environment for building highly scalable server-side
application using JavaScript.
Node.js eliminates the waiting, and simply continues with the next request.
REACT
React is a free and open-source front-end JavaScript library for building
user interfaces based on components.
It is maintained by Meta and a community of individual developers and
companies.
React can be used to develop single-page, mobile, or server-rendered
applications with frameworks like Next.js.
React is a JavaScript-based UI development library.
Although React is a library rather than a language, it is widely used in
web development
Why React?
React‟s popularity today has eclipsed that of all other front-end development
frameworks. Here is why:
ReactJS Advantages
Limitations
Features of React
Re-usability
Nested components
Render method
Passing properties
React offers some outstanding features that make it the most widely
The above code shows how JSX is implemented in React. It is neither a string
nor HTML. Instead, it embeds HTML into JavaScript code.
Architecture
In a Model View Controller(MVC) architecture, React is the 'View'
responsible for how the app looks and feels.
React Native:
React Native is a framework that lets you build native mobile apps with
React.js. It is essentially a cross-platform framework that allows you to use
the same code to build apps for both iOS and Android.
DJANGO
Django is a free and open-source Python web framework that encourages rapid
development and clean, pragmatic design. It takes care of much of the hassle of
web development, so you can focus on writing your app without needing to
reinvent the wheel.
Django
AngularJS
Business websites
Educational websites
UI/UX DESIGN
UX stands for user experience. It refers to the overall experience that a user has
when using a website or application. This includes the UI, but it also includes
factors such as usability, performance, and customer support. A good UX makes
it easy for users to find what they are looking for and complete their tasks.
UI/UX and AngularJS are both important aspects of building web applications.
UI/UX is about making sure that the application is easy to use and understand,
while AngularJS is a framework that can be used to build SPAs that provide a
fluid and responsive user experience.
Here are some of the ways that UI/UX and AngularJS can be used together
to build better web applications:
************