[go: up one dir, main page]

0% found this document useful (0 votes)
55 views236 pages

It3401 - We Course File

The document outlines the course file for IT3401 Web Essentials at St. Peter's College of Engineering & Technology, Chennai, detailing the syllabus, lesson plans, and practical exercises. It covers key topics such as web programming, client-server models, HTML, CSS, JavaScript, PHP, and database connectivity. The course aims to equip students with the skills to create interactive websites and applications using various web technologies.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views236 pages

It3401 - We Course File

The document outlines the course file for IT3401 Web Essentials at St. Peter's College of Engineering & Technology, Chennai, detailing the syllabus, lesson plans, and practical exercises. It covers key topics such as web programming, client-server models, HTML, CSS, JavaScript, PHP, and database connectivity. The course aims to equip students with the skills to create interactive websites and applications using various web technologies.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 236

ST.

PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI


Affiliated to Anna University, Chennai & Approved by AICTE

REGULATION 2021
IT3401
WEB ESSENTIALS
COURSE FILE
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

COURSE FILE CONTENTS

1. TIME TABLE

2. SYLLABUS

3. LESSON PLAN

4. COURSE MATERIAL

5. UNITWISE – 2MARKS & 16 MARKS

6. ASSESSMENT QUESTION PAPER -1

7. ANSWER KEY - 1

8. ASSESSMENT QUESTION PAPER -2

9. ANSWER KEY -2
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

TIME TABLE

Ms. D.Sujatha

1 2 3 4 5 6 7
Days /
Hours 10.35- 03.05-
08.30-09.30 09.30-10.25 11.30-12.25 01.15-02.10 02.10-03.05
11.30 04.00

MON IT3401 WE LAB

IT3401
TUE
WE

WED

IT3401
THU
WE

IT3401 IT3401
FRI
WE WE

SAT

Subject Code Subject Name Branch Year Sem Hours

IT3401 Web Essentials Theory & Lab IT II IV 6

Staff in Charge HOD / IT


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

SYLLABUS

IT3401 WEB ESSENTIALS LTPC

3024

COURSE OBJECTIVES:

 To comprehend and analyze the basic concepts of web programming and internet protocols.

 To describe how the client-server model of Internet programming works.

 To demonstrate the uses of scripting languages

 To write simple scripts for the creation of web sites

 To create database applications

UNIT I WEBSITE BASICS 9

Internet Overview - Fundamental computer network concepts - Web Protocols - URL – Domain Name-
Web Browsers and Web Servers- Working principle of a Website –Creating a Website - Client-side and
server-side scripting

UNIT II WEB DESIGNING 9

HTML – Form Elements - Input types and Media elements - CSS3 - Selectors, Box Model, Backgrounds
and Borders, Text Effects, Animations, Multiple Column Layout, User Interface.

UNIT III CLIENT-SIDE PROCESSING AND SCRIPTING 9

JavaScript Introduction – Variables and Data Types-Statements – Operators - Literals-Functions- Objects-


Arrays-Built-in Objects- Regular Expression, Exceptions, Event handling, Validation - JavaScript
Debuggers.

UNIT IV SERVER SIDE PROCESSING AND SCRIPTING – PHP 9

PHP - Working principle of PHP - PHP Variables - Constants - Operators – Flow Control and Looping -
Arrays - Strings - Functions - File Handling - File Uploading – Email Basics - Email with attachments -
PHP and HTML - Simple PHP scripts - Databases with PHP

UNIT V SERVLETS AND DATABASE CONNECTIVITY 9

Servlets: Java Servlet Architecture – Servlet Life cycle- Form GET and POST actions -Sessions – Cookies
– Database connectivity - JDBC
Creation of simple interactive applications - Simple database applications
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
PRACTICAL EXERCISES:
1. Creation of interactive web sites - Design using HTML and authoring tools
2. Form validation using JavaScript
3. Creation of simple PHP scripts
4. Handling multimedia content in web sites
5. Write programs using Servlets:
i. To invoke servlets from HTML forms
ii. Session tracking using hidden form fields and Session tracking for a hit count
6. Creation of information retrieval system using web, PHP and MySQL
7. Creation of personal Information System

COURSE OUTCOMES:

At the end of this course, the students will be able to:


CO 1: Apply JavaScript, HTML and CSS effectively to create interactive and dynamic websites.
CO 2: Create simple PHP scripts
CO 3: Design and deploy simple web-applications.
CO 4: Create simple database applications.
CO 5: Handle multimedia components

TEXT BOOKS

1. Robin Nixon, "Learning PHP, MySQL, JavaScript, CSS & HTML5" Third Edition, O'Reilly publishers,
2014.
2. Paul Deitel, Harvey Deitel, Abbey Deitel, “Internet & World Wide Web - How to Program”, 5th
edition, Pearson Education, 2012.

REFERENCES:

1. Jeffrey C. Jackson, "Web Technologies--A Computer Science Perspective", Pearson Education, 2006.
2. James F. Kurose, “Computer Networking: A Top-Down Approach”, Sixth Edition, Pearson Education,
2012
3. Steven Holzener , “PHP – The Complete Reference”, 1st Edition, Mc-Graw Hill, 2017
4. Fritz Schneider, Thomas Powell , “JavaScript – The Complete Reference”, 3rd Edition, Mc- Graw Hill
Publishers, 2017
5. Bates, “Developing Web Applications”, Wiley Publishers, 2000
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
LESSON PLAN

Total periods Conducted: 58

Unit – 1

Executed Reason POs/


Planned For
No. Topic Pedagogy Resource Date/ COs
Date/ Period PSOs
Period Deviation

1 07-02-2023/4 Internet Overview BB T1 7-2-23/4 1 1

9,10,11
OF FEB
Fundamental Computer
2 09-02-2023/2 BB T1 14-2-23/4 MONTH 1 1,5
Network Concepts
TAKEN
LEAVE

3 10-02-2023/1 Web Protocols BB T1 15-2-23/1 1 1,5

4 10-02-2023/6 URL BB T1 16-2-23/2 1 1

5 11-02-2023/3 Domain Name BB,PPT T1 17-2-23/1 1 1,5

Web Browsers And Web


6 14-02-2023/4 BB,PPT T1 17-2-23/6 1 1,3,5
Servers

Working Principle Of A
7 16-02-2023/2 BB,PPT T1 18-2-23/3 1 3,5
Website

Creating A Website PPT,


8 17-02-2023/1 T1 21-2-23/3 1 2,3,5
DEMO

BB,
9 17-02-2023/6 Client-Side Scripting T1 21-2-23/4 1 2,3,5
DEMO

BB,
10 18-02-2023/3 Server-Side Scripting T1 22-2-23/1 1 2,3,5
DEMO

SLIP
11 21-02-2023/4 Revision 22-2-23/7
TEST

Unit -2

Executed Reason
For
No. POs/
Planned
Topic Pedagogy Resource Date/ COs
Date/ Period PSOs
Period Deviation

12 Web Designing 23-02-


23-02-2023/2 PPT T1 2 3,5
2023/2

13 24-02-
24-02-2023/1 Form Element PPT,DEMO T1 2 3,5
2023/1

14 Input types and Media 24-02-


24-02-2023/6 BB T1 2 1,2,3
elements 2023/6
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

15 CSS3 25-02-
25-02-2023/3 BB T1 2 1,2,3
2023/3

16 Selectors 28-02- 1,2,3


28-02-2023/4 BB T1 2
2023/4

Box Model Backgrounds 02-03-


17 02-03-2023/2 BB T1 2 1,2,3
and Borders 2023/2

3-3-23 -
18 03-03-2023/1 Text Effects PPT T1 4-3-23/3 TAKEN 2 1,2,3
LEAVE

19 03-03-2023/7 Animation PPT T1 6-3-23/3 2 1,2,3

Multiple Column Layout


20 04-03-2023/3 PPT T1 6-3-23/4 2 1,2,3
Website Creation

21 07-03-2023/4 User Interface PPT T1 7-3-23/4 2 1,2,3

22 09-03-2023/2 Revision SLIP TEST 9-3-23/2

Unit- 3

Planned Executed POs/


Reason For
No. Date/ Topic Pedagogy Resource Date/ COs
Deviation PSOs
Period Period

23 10-03- JavaScript Introduction PPT T1 10-3-23/1 3 1,2


2023/1

10-03- Variables and Data


24 PPT,DEMO T1 10-3-23/6 3 1,2
2023/6 Types-Statements

11-3-23 TO
25 30-03- Operators BB T1 30-3-23/6 28-3-23 3 1,2,5
2023/2
ASSESSMENT

26 31-03-
1-4-23/3 31-3-23
2023/1
Literals Functions, Object BB T1 TAKEN 3 1,2,5
27 31-03- LEAVE
6-4-23/2
2023/6

28 01-04- Arrays BB R3 8-4-23/3 3 1,2


2023/3

29 06-04- Build-in Object BB R3 10-4-23/3 3 2,3


2023/2

30 08-04-
Regular Expression BB R3 3 2,3,5
2023/3

31 11-04-
Exceptions BB R3 3 2,3
2023/4
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

32 13-04-
Event Handling PPT R4 3 2,3
2023/2

33 15-04- R3
JS Debuggers BB 3 2,3
2023/3

18-04- Sample programs for Java R3


34 PPT 3 2,3,5
2023/4 script

20-04-
35 Revision SLIP TEST
2023/2

Unit- 4

Executed Reason
Planned For POs/
No. Date/ Topic Pedagogy Resource COs
Date/ PSOs
Period
Period Deviation

21-04-
36
2023/1 PHP
PPT T1 4 1,2,3,4,5
21-04- Working principle of PHP
37
2023/6

38 22-04- PPT,
PHP Variables T1 4 2,3
2023/3 DEMO

25-04-
39 Constants BB T1 4 2,3,5
2023/4

40 27-04-
Operators BB T1 4 2,3,5
2023/2

25-04-
41 Flow Control and Looping BB T1 4 2,3
2023/4

28-04-
42 Arrays – Strings BB T1 4 2,3,5
2023/1

28-04-
43 Functions – File Handling PPT/BB T1 4 2,3,5
2023/6

29-04- File Uploading – Email Basics


44 PPT T1 4 2,3,5
2023/3 – Email with attachments

02-05- PHP and HTML – Simple


45 PPT T1 4 3,4,5
2023/4 PHP scripts

04-05-
46 Databases with PHP DEMO T1 4 3,5
2023/2

05-05- SLIP
47 Revision
2023/1 TEST
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
Unit- 5

Executed Reason
No. For POs/
Planned
Topic Pedagogy Resource COs
Date/ Period Date/ PSOs
Period Deviation

48 05-05-2023/6 Servlets PPT T2 5 2,3,4,5

49 06-05-2023/3 Java Servlet Architecture PPT, DEMO R4 5 1,2,3

50 16-05-2023/4 Servlets Life Cycle BB R4 5 1,2,3

51 18-05-2023/2 Form GET and POST


BB R4 5 2,3,4,5
actions

52 19-05-2023/1 Sessions , Cookies BB T2 5 3,4,5

53 19-05-2023/6 Database connectivity BB R4 5 3,4,5

Review of Basic Data


Analytic Methods using
54 20-05-2023/3 R BB T1 5 3,5

JDBC

55 23-05-2023/4
Creation of simple PPT /
T2 5 3,5
interactive application BB/DEMO
56 25-05-2023/2

57 26-05-2023/1 Simple Database


DEMO T2 5 3,5
Application

58 26-05-2023/6 Revision SLIP TEST

List of Pedagogies: Chalk & Talk/ Quiz/ MCQs/ Flipped Class/ Demonstration/ Site Visit/ Role Play/ Video/

Discussion/ Tutorial/ Any other

TEXT BOOK(S):

T1. Robin Nixon, “Learning PHP, MySQL, JavaScript, CSS & HTML5” Third Edition, O’Reilly publishers, 2014.

T2. Paul Deitel, Harvey Deitel, Abbey Deitel, “Internet & World Wide Web – How to Program”, 5th edition, Pearson
Education, 2012.

REFERENCES:

R1. Jeffrey C. Jackson, “Web Technologies–A Computer Science Perspective”, Pearson Education, 2006.
R2. James F. Kurose, “Computer Networking: A Top-Down Approach”, Sixth Edition, Pearson Education, 2012
R3. Steven Holzener , “PHP – The Complete Reference”, 1st Edition, Mc-Graw Hill, 2017
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
R4. Fritz Schneider, Thomas Powell , “JavaScript – The Complete Reference”, 3rd Edition, McGraw Hill Publishers,
2017
R5. Bates, “Developing Web Applications”, Wiley Publishers, 2006

Prerequisite Courses:
 Basic knowledge in Java, HTML and Web Services

Course Objective  Understand about client-server communication and protocols used during
communication.
 Design interactive web pages using Scripting languages.
 Learn server side programming using servlets and JSP.
 Develop web pages using XML/XSLT.
The students will be able to,
CO1: Design simple web pages using HTML and XHTML.
Course Outcomes CO2: Design & develop dynamic web pages using DHTML & Java script.
CO3: Experiment with server side programming using DOM & Servlet.
CO4: Develop web applications using JSP & construct web data using XML.
CO5: Understand web services & identify the interactions among web services.

POs PSOs
COs PO- PO- PO- PO- PO- PO- PO- PO- PO- PO- PO- PO- PSO- PSO PSO
1 2 3 4 5 6 7 8 9 10 11 12 1 -2 -3

CO- 3 2 3 2 3 2 0 0 2 2 2 3 3 2 1
1

CO- 3 3 3 3 3 2 0 0 2 0 2 3 3 2 1
2

CO- 3 3 3 2 3 2 0 0 2 2 2 3 3 2 1
3

CO- 3 3 3 3 3 1 0 0 1 1 2 3 3 2 1
4

CO- 3 3 3 3 3 1 0 0 0 0 2 3 3 2 1
5
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
COURSE MATERIAL – IT3401 WEB ESSENTIALS

UNIT I

Internet Overview - Fundamental computer network concepts - Web Protocols - URL – Domain Name-
Web Browsers and Web Servers- Working principle of a Website –Creating a Website - Client-side and
server-side scripting

Introduction:

1.1Internet Overview :

Server:

The software that distributes the information and the machine where the inf rmati n and s ftware
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, comm nicates with the server, fetches the
information, processes it, and then displays it on the remote m chine is c lled the client.

initiates contact with server (―speaks first‖)


typically requests service from server
Web: client implemented in browser

Web server:

Software that delivers Web pages a d other documents to browsers using the HTTP protocol

Web Page:

A web page is a docum nt or source of information that is suitable for the World Wide Web and
can be accessed through a w b b ows .

Website:
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
A collection of pages on the World Wide Web that are accessible from the same URL and typically
residing on the same server

URL:

Uniform Resource Locator, the unique address which identifies a resource on the Internet for
routing purposes.

1.2 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.

A server process, running on a server host, provides access to a service. A client process, running
on a client host, accesses the service via the server process.The interaction of the process proceeds
according to a protocol.
The primary idea of a client/server system is that you have a central repository of

information—some kind of data, often in a database—that you want to distribute on demand to so e set of
people or machines.

1.3 The Internet:


• Medium for communication and interaction in inter connected network.

• Makes information constantly and instantly available to anyone with a onne ti n.

Web Browsers:

User agent for Web is called a browser:


o Internet Explorer
o Firefox

Web Server:
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
Server for Web is called Web
server: o Apache (public
domain)
o MS Internet Information Server

Protocol:
Protocols are agreed formats for tra sm tt g data between devices.

The protocol determines:


i. The error checking requ red
Data compr ssion m thod used
The way the nd of a m ssage is signalled
The way the d vice indicat s that it has received the message

1.4 Internet Protocol:

There are many protocols used by the Internet and the WWW:

TCP/IP
o HTTP
o FTP

o Electronic mail protocols


IMAP o POP
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

TCP/IP

The Internet uses two main protocols (developed by Vincent Cerf and Robert Kahn) Transmission
control protocol (TCP):Controls disassembly of message into packets at the origin

reassembles at the destination

Internet protocol (IP):Specifies the addressing details for each packet Each packet is labelled with
its origin and destination.

1.5 Hypertext Transfer Protocol (HTTP)

• The hypertext transfer protocol (HTTP) was developed by Tim Berners-Lee in 1991
HTTP was designed to transfer pages between machines

The client (or Web browser) makes a request for a given page and the Server is responsible for
finding it and returning it to the client
The browser connects and requests a page from the server
The server reads the page from the file system, sends it to the client and
terminates the connection.

Electronic Mail Protocols:


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Electronic mail uses the client/server model

The organisation has an email server devoted to handling email


o Stores and forwards email messages

Individuals use email client software to read and send email


o (e.g. Microsoft Outlook, or Netscape Messenger)
• Simple Mail Transfer Protocol (SMTP)

o Specifies format of mail messages


• Post Office Protocol (POP) tells the email server to:
o Send mail to the user’s computer and delete it from the server

o Send mail to the user’s computer and do not delete it from the server
o Ask whether new mail has arrived.

1.6 Interactive Mail Access Protocol (IMAP)

Newer than POP, provides similar functions with additional features.


o e.g. can send specific messages to the client rather than all the messages.

A user can view email message headers and the sender’s name before
downloading the entire message.
Allows users to delete and search mailboxes held on the email server.

The disadvantage of POP: You can only access messages from one PC

The disadvantage of IMAP :Since email is stored on the email server, there is a need for more and more
expensive (high speed) storage space.

1.7 World Wide Web: comprises software (Web server and browser) and data (Web sites).

Internet Protocol (IP) Addresses:


Every node has a unique numeric address
Form: 32-bit binary number
New standard, IPv6, has 128 bits (1998)
Organizations are assigned groups of IPs for their com uters
Domain names
Form: host-name. domain-names
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
First domain is the smallest (Google)
- Last domain specifies the type of orga zat on (.com)
Fully qualified domain name - the host name and all of the domain names
DNS servers - conv rt fully qualifi d domain names to IPs

1.8 HTTP:
Hypertext T ansf P otocol (HTTP) is the communication protocol used by the Internet to
transfer hype text documents.

A protocol to transfer hypertext requests and information between servers and browsers
Hypertext is text, displayed on a computer, with references (hyperlinks) to
other text that the reader can immediately follow, usually by a mouse HTTP is behind every request for a
web document or graph, every click of a hypertext link, and every submission of a form.

HTTP specifies how clients request data, and how servers respond to these requests.

The client makes a request for a given page and the server is responsible for finding it and
returning it to the client.
The browser connects and requests a page from the server.
The server reads the page from the file system and sends it to the client and then
terminates the connection

HTTP Transactions
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
1.9 HTTP Message:

HTTP message is the information transaction between the client and server.

o types of HTTP Message:

Requests
Client to server
Responses
Server to client
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Fields
Request line or Response line
General header
Request header or Response header
Entity header
Entity body

1.10 Request Message:

Request Line:

A request line has three parts, separated by spaces


o a method name
o the local path of the r qu sted resource o
the ve sion of HTTP b ing used

A typical request line is:


GET /path/to/fil /ind x.html HTTP/1.1

Notes:
GET is the most common HTTP method; it says "give me this resource". Other
methods include POST and HEAD. Method names are always uppercase

The path is the part of the URL after the host name, also called the request
URI o The HTTP version always takes the form "HTTP/x.x", uppercase.

Request Header:
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

1.11 Response Message:


Response Line:

A request line has three parts, separated by spaces


o the HTTP version,

o a response status code that gives the result of the request,


and o an English reason phrase describing the status code

Typical status lines are:


o HTTP/1.0 200 OK or
o HTTP/1.0 404 Not Found
• Notes:

o The HTTP version is in the same format as in the request line, "HTTP/x.x".

o The status code is meant to be computer-readable; the reason phrase is meant to be


human-readable, and may vary.

HTTP Request Header:


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
EXAMPLE

HTTP Method:

HTTP method is supplied in the request line and specifies the operation that the client has
requested.

Some common methods:


Options
Get
Head
Post
Put
Move
Delete
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Two methods that are mostly used are the GET and POST:
o GET for queries that can be safely repeated

o POST for operations that may have side effects (e.g. ordering a book from an on-line store).

The GET Method

It is used to retrieve information from a specified URI and is assumed to be a safe, repeatable
operation by browsers, caches and other HTTP aware components
Operations have no side effects and GET requests can be re-issued.

For example, displaying the balance of a bank account has no effect on the account and can be
safely repeated.

Most browsers will allow a user to refresh a page that resulted from a GET, with ut displaying
any kind of warning
Proxies may automatically retry GET requests if they encounter a temp rary netw rk c nnection
problem.

GET requests is that they can only supply data in the form of parameters en oded in the URI
(known as a Query String) – [downside]

Cannot be unused for uploading files or other operations that req ire arge amounts of data to be
sent to the server.

The POST Method

Used for operations that have side effects and c nnot be s fely repeated.

For example, transferring money from one b nk ccount to nother has side effects and should not
be repeated without explicit approval by the user.

If you try to refresh a page in I ter et Ex lorer that resulted from a POST, it displays the
following message to warn you that there may be s de effects:
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
The POST request message has a content body that is normally used to send
parameters and data

• The IIS server returns two status codes in its response for a POST request

o The first is 100 Continue to indicate that it has successfully received the POST request
o The second is 200 OK after the request has been processed.

HTTP response status codes

Informational (1xx)
Successful (2xx)
Redirection (3xx)
o 301: moved permanently

• Client error (4xx)


o 403 : forbidden
o 404: Not found
• Server error (5xx)

o 503: Service unavailable


o 505: HTTP version not supported

1.12 HTTP
Features

Persistent TCP Connections: Remain open for multiple requests


Partial Document Transfers: Clients can specify start and stop positions
Conditional Fetch: Several additional conditions
Better content negotiation
More flexible authentication.

Web Browsers :

• Mosaic - NCSA (Univ. of Illinois), in early 1993 First to se a GUI, ed to Explosion of Web use
Initially for X-Windows, under UNIX, but was ported to other platforms by ate 1993

Browsers are clients - always initiate, servers react (altho gh sometimes servers require
responses)
Most requests are for existing documents, using Hypertext Tr nsfer Protocol
(HTTP) But some requests are for program execution, with the output being
returned as a document.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
Browser: A web browser is a software application for retrieving, resenting, and
traversing information resources on the World Wide Web.

Web Servers:

Provide responses to browser requests, e ther existing documents or dynamically Built


documents.
Browser-server conn ction is now maintained through more than one request- Response cycle
- All communications b tw n brows rs and servers use Hypertext Transfer Protocol
Web servers un as backg ound proc sses in the operating system.

Monitor a communications po t on the host, accepting HTTP messages when they appear
All current Web serve s came f om either
1. The original from CERN
2. The second one, from NCSA
Web servers have t o main directories:
Document root (servable documents)
Server root (server system software)
Document root is accessed indirectly by clients
Its actual location is set by the server Configuration file
Requests are mapped to the actual location
Virtual document trees
Virtual hosts
Proxy servers
Web servers now support other Internet protocols
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Apache (open source, fast, reliable)


IIS
Maintained through a program with a GUI interface.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
Unit - II – HTML

HTML – Form Elements - Input types and Media elements - CSS3 - Selectors, Box Model, Backgrounds
and Borders, Text Effects, Animations, Multiple Column Layout, User Interface.

Markup Language:

Mark-up Language is used to identify elements of a page so that a browser can render that page on
your computer screen.

Content to be displayed is ―marked up‖ or tagged to tell the browser how to display it.

A markup language is a set of characters or symbols that define a document’s logical structure or how a
document should be printed or displayed.

Hyper Text Markup Language:

Hyper Text Mark-up Language, the language used to create documents on the W rld Wide Web.

HTML is a collection of styles (indicated by mark-up tags) that define the various elements of a
World Wide Web document.

HTML is based on an older language called Standard Genera ized Markup Language, or
SGML, which defines the data in a document independently of how the data will be displayed.

· HTML document can be read and displayed by m ny different browsers running on different types
of computers – platform independent!

HTML defines the structure and layout of the elements on a Web page with a variety of tags.

Each tag may have a set of attr butes that modify the a pearance or layout of the visual element
contained by the tag.

HTML is a plain-text file that can be created using a text editor like Notepad.

HTML is a p og amming language that allows you to tell the browser what you want it to display
and how you want it to be display d, in simple terms, it is a Webpage.

HTML there a e ce tain ma kers, like commands, that tell the Browser what to do, these are called
tags. By using tags you can have tables, fonts, colors, pictures, links, and almost anything you can think up,
and experimentation with tags can lead to some pretty cool WebPages.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
1.13 HTML History:

The first version of HTML was created using the Standard Generalized Mark up Language
(SGML).

In the early years of HTML, Web developers were free to define and modify HTML in whatever
ays they thought best.

Competing browsers introduced some differences in the language. The changes were called
extensions.

A group of Web developers, programmers, and authors called the World Wide Web
Consortium, or the WC3, created a set of standards or specifications that all browser manufacturers were
to follow.

The WC3has no enforcement power.

The recommendations of the WC3are usually followed since a uniform approach to Web page
creation is beneficial to everyone.

Co m parison of H T M L versions:
HTML 3 HTML 4 HTML 5

<body> <body> <body>

<table> <div id="header">...</div> <header> </header>

<tr> <div id="nav">...</div> <nav>...</nav>

<td>header</td> <div class="right"> <right>

</tr> ... ...

<tr> </div> </right>

<td>nav</td> <div d="left">...</div> <left>...</left>

</tr> <div d="footer">...</div> <footer>...</footer>

<tr> </body> </body>

<td>left </td>

<td> right </td>

</tr>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

HTML Basics:

HTML is primarily composed of two types of markup:


• Elements or tags
<html></html>
Attributes that modify an element

HTML Elements

Elements are the fundamental building blocks of HTML.


They are the tags that tell the browser what the enclosed text is.

HTML Tags:

• Container Tags
o <Begin formatting>some text</End formatting>

o For example: <B>some bold text</B>


<H1>some heading </H1>
• Empty Element Tags
o For example <HR> <BR>
• Comment Tag
o <!-- Hi, I'm a comment. -->
o Use them document complicated layouts!
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Case insensitive
Unrecognised tags are simply ignored by browser!!
Container tags must be nested!!

As a text document, your HTML in Notepad will contain elements, such as headers, titles, paragraphs,
etc.
These elements must be denoted in your script, which is done using tags
HTML tags consist of a left angle bracket (<), a name, and a right angle bracket(>)
For example: <title>
Tags must also close. To do so, you incorporate a slash (/). A starting and ending tag would be: <title>
</title>.

Attributes:

You can add attributes to tags to enhance your page.


Added attributes go inside the brackets of the opening tag(example: <p align=center> would
center the paragraph)

About HTML file Structure:

· HTML files .htm or .html extensions


· Name your files to describe their functionality file name of your home page should be index.ht l
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Common Tags (Elements):


Always include the <HTML>…</HTML> tags
Comments placed inside <!--…--> tags
HTML documents
o HEAD section.
Info about the document.
Info in header not generally rendered in display
window. o TITLE element names your Web page.
o BODY section

Page content
Includes text, images, links, forms, etc.
Elements include backgrounds, link colors nd font f ces
P element forms a paragraph, blank line before and after

Structure of HTML Tag (Element) Al g me t

Text Styling

Underline style<U>…</U>
Align elements with ALIGN attributeright, left or center
Close nested tags in the reverse order from which they were opened
Emphasis (italics) style<EM>…</EM>
Strong (bold) style<STRONG>…</STRONG>
<B> and <I> tags deprecated Overstep boundary between content and presentation
Logical Styles:
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

o <EM>, <STRONG> a add emphasis to text


o <BIG>, <SMALL> a increase or decrease text size

o <SUB>, <SUP> a subscript or superscript


• Physical styles:
o <B>, <I>, <U> a Bold, Italics, and Underline text

o <FONT SIZE=# FACE= ―name‖ COLOR=―colorName or #rgb‖


> o E.g., <FONT SIZE=+2 FACE = ―arial‖ COLOR =
―darkblue‖>

eXtensible Mark up Language (XHTML) :

To describe the general form and layout of documents


An XHTML document is a mix of content and controls

In XHTML tag names, attributes, and values are case sensitive and values must be encl sed by
double quotes.
In XHTML all elements must have both beginning and ending tags
Controls are tags and their attributes

o Tags often delimit content and specify something about how the content
o should be arranged in the document.

o Attributes provide additional information about the content of a tag.


Tools for creating XHTML documents
o XHTML editors - make document creation e sier
o Shortcuts to typing tag names, spell-checker,

o WYSIWYG XHTML editors


Plug ins
o Integrated into tools like word processors,
o effectively converting them to WYSIWYG

o XHTML editors
Filters
o Convert documents in other formats to XHTML
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Advantages of both filters and plug-ins:

Existing documents p oduc d with other tools


can be conve ted to XHTML docum nts
Use a tool you al eady know to produce XHTML

Disadvantages of both filters and plug-ins:

XHTML output of both is not perfect - must be fine tuned


XHTML may be non-standard
You have t o versions of the document, which are difficult to synchronize

Relative URL

HTML Link:

To create a link to a resource identifiable by a URL


o href: specify a URL of the target resource

o target: specify where to display the target document

e.g.: <a href="index.htm"


target="_blank">Home</a> Open the document "index.htm" in a
new browser window

Can also be used to create an anchor within a document


o name: specify the anchor name

e.g.: <a name="chap1"></a><h2>Chapter 1</h2>


The above anchor can be referred to in a URL as

<a href="http://host/file.html#chap1">Chapter 1</a>

URL (Uniform Resource Locator) in HTML:

URL is used to create a link in a web document.


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
Two Types of URL:

1. Absolute URL

• Absolute URL contains all the information necessary to identify files on the internet (Example: in
postal service, for sending letter to the destination it necess ry to have f ll information like, name, address,
city etc.,)

Likewise, an absolute URL contains the protocol, hostn me, filename, which are all essential to
link the web document.
Example:
http://google.com/index.html

1.14 Relative URL

Relative URL contains the only the folder name and filename or even just the file name.
Browser does not n d protocol addr ss or server name to identify the file in the web.
• Relative URL to f the docum nts in relation to the originating document.

Two types of Relative URL:

i. Document – Relative URL

Document Relative URL is used to relate the HTML document in the same folder, just providing
the name of the file (ex: Index.html).
It contains only the folder name and file name.
Server – Relative URL
Server relative URL is relative to the server root.
It contains the part of URL and relating to the host name.

Anchors and Links

This section discusses the A tag which is used to define anchors (places in a document that can be
linked to) and also to create links.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

A - (anchor or link)

The A tag lets you define anchors and links. An anchor defines a place in adocument. A link
displays a hypertext link that the user can click to display an anchor or a document.

A as anchor

An anchor identifies a place in an HTML document. To indicate that an <A> tag is being used as
an anchor, specify the NAME attribute.

Note that you can also use the ID attribute of any tag to identify that tag as an anchor, as discussed
in UNIVERSAL Attributes.

Do not nest an anchor within another A tag.

Syntax
<A

NAME="anchorName"

>.
..
</A>

Example
<A NAME=section2>

<H2>A Cold Autumn Day</H2></A>

If this anchor is in a file called "nowhere.htm," you could define link that jumps to the anchor as
follows:
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

<P>Jump to the second section <A HREF=" owhere.htm#section2">


A Cold Autumn Day</A> in the mystery "A man from Nowhere."

A as link

A hypertext link is a piece of content that the user can click to invoke an action.

The most common actions are scrolling to a different place in the current document and opening a
new document.
A hypertext link can contain t xt and/or graphics.

To define a hype t xt link, use the <A> tag with an HREF attribute to indicate the start of the
hypertext link, and use the </A> tag to indicate the end of the link.
When the user clicks any content between the <A HREF> and </A> tags, the link is activated.
The value of the HREF attribute must be a URL.
• If you ant the link to open a new document, the value of HREF should be the URL for the

destination document.
• If you ant to scroll the current document to a particular place, the value of HREF should be the
name of the anchor to which to scroll, preceded by the # sign.
• If you ant to open another document at an anchor, give the URL for the document, followed by
#, follo ed by the name of the anchor.

If you want the destination document or anchor to open in a separate browser window, supply the
name of the window as the value of the TARGET attribute.
If the named window does not already exist, a new window opens.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

The link can also do actions other than opening and scrolling documents. It can send mail
messages, point to files located on FTP servers, run any arbitrary JavaScript code, open local files, point to
a gopher server, or read news groups.

To do any of these actions, you specify an appropriate kind of URL, such as a mailto URL to
send a mail message or a news URL to read a news group.

Most browsers display hypertext links in a color different from that of the rest of the document so
that users can easily identify them.

You can also define actions that occur when the mouse cursor enters or leaves the region
containing the link by specifying onMouseOver and onMouseOut event handlers for the link.

• Additionally, you can specify an onClick event handler that determines the action to occur when
the user clicks a link.

A link that has not been clicked is called an unvisited link.


A link that has been clicked is known as a visited or followed link.
A link that is in the process of being clicked is an active link.

Syntax

<A
HREF="location"
ONCLICK="clickJScode"
ONMOUSEOUT="outJScode"
ONMOUSEOVER="overJScode"
TARGET="windowName"
>
...
</A>
HREF="location" specifies a destinat on URL for the li k. The most common value here is a

document name or an anchor. To spec fy a docume t to open, provide the URL for the document, either as
an absolute or relative URL.

An example of an absolute URL is:


HREF="http://www.ch nnaikavigal.com/index.html"

An example of a elative URL is:


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
HREF="p oducts/doc1.html"

To scroll the current document to an anchor, give the name of the anchor preceded by the pound

sign. For example:


HREF="#anchor1
"

To open a different document at an anchor, give the URL for the document, followed by the # sign
follo ed by the name of the anchor. For example:

HREF="products/doc1.html"

The HREF attribute can also be a URL that sends a message, points to files located on an FTP
server, runs arbitrary JavaScript code, opens local files, points to a gopher server, or reads news groups.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

ONCLICK="clickJScode" specifies JavaScript code to execute when a user clicks the link. If you supply
a value for the ONCLICK attribute, the specified action overrides the default link behavior.

ONMOUSEOUT="outJScode" specifies JavaScript code to execute when a user moves the mouse
cursor out of the link or anchor.

ONMOUSEOVER="overJScode" specifies JavaScript code to execute when a user oves the ouse
pointer over the image or link text.

TARGET="windowName" specifies a window in which to show the destination d cu ent (if the link's
action is to scroll or open a document). If the named window is not already open, a new wind w with that
name opens.

Special target values are:

blank opens the destination document in a new unnamed window

parent opens the destination document in the parent window of the one displaying the current
document.

self opens the destination document in the same window s the one in which the link was clicked.
top opens the destination document in the full body of the current window. This value can be used

to ensure that the destination document takes over the full window even if the original document was
displayed in a frame.

Example

<P>You can find all the latest news from Chennai Kavigal at
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
<A HREF="http://www.ch nnaikavigal.com/index.html">Chennai Kavigal's
Home Page</A>.

HTML List:

Lists can add a lot to a WebPage, there are different types of lists and
different types of bullets or numbers that can be used.

You can have an ordered list (a, b, c, etc.) unordered lists (with bullets) or you
can have definition lists.

This section describes the tags for displaying lists:


DIR, DL, DT, DD, MENU, OL, UL, LI

DIR - (directory list)

The DIR tag is intended to display a list of short items such as in a directory listing.
In practice, the DIR tag usually does the same thing as the UL (unordered list) tag.

To mark the individual items within the list, use the LI tag. A single list item can
contain additional paragraphs, marked with the P tag.

This tag is being deprecated; that is, it has become obsolete.


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Syntax
<DIR>

...

</DIR>

Example

<P>The directory structure is:</P>


<DIR>

<LI>PRODUCTS
<DIR>
<LI>SHAKTHI.htm
<LI>TYPING TUTOR.htm
</DIR>
<LI>MULTIMEDIA

<DIR>

<LI>KURALAMUDHU.htm
<LI>ARIVODU VILAYADU.htm
</DIR>
<DIR>

DL - (definition list)

The DL tag encloses a definition list. A definition list contains terms, which are defined with the
DT tag, and definitions, which are defined with the DD tag. By default, Nadodi aligns

terms on the left and indents each def n t on on a ew li e. However, you can use the COMPACT attribute
to display a definition on the same line as the precedi g term, if it fits on one line.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

The intent of a definition list s to d splay l sts of terms and their corresponding definitions, such as
in a glossary.

Syntax
<DL COMPACT>

...
</DL>

COMPACT compacts the definition list by placing the term defined by the DT tag on the same line as the
definition defined by the DD tag, provided the term is short enough.

Definition List Example

The follo ing example defines six HTML terms.

<DL>
<DT>HTML
<DD>This tag marks a text file as an HTML document.
<DT>HEAD
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

<DD>This tag encloses the heading for the HTML document.

<DT>BODY
<DD>This tag displays the body for the HTML document.
<DT>DL
<DD>This tag displays a definition list in the HTML document.
<DT>DT
<DD>This tag displays a term in a definition list.
<DT>DD
<DD>This tag displays a definition description.
</DL>

DT - (definition term)

The DT tag specifies a term in a definition list. The DT tag must be used in a DL tag. Usually a DT
tag is followed by a DD tag that describes the term in the DT tag.

The DT tag does not require a closing tag.

Syntax <DT>

Used Within <DL>

DD – (Definition description)
The DD tag displays a definition description in definition list. The DD tag must be used

within a DL tag and usually follows immediately after DT t g th t indicates the term being defined. The
DD tag does not require a closing tag.
See DL for more details and an example.

Syntax <DD>
Used Within <DL>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

MENU - (list of simple items)

The MENU tag displays a list of simple items. This tag works just like the UL tag. Use the LI tag
to designate the individual m nu it ms.

This tag is being dep cat d b cause it has become obsolete in favor of the UL tag.

Syntax
<MENU>

...
</MENU>

Example
The follo ing example creates a list of three short items:

<P>Menu Example:</P>

<MENU>
<LI> Windo s 9x
<LI> Windo s NT

<LI> Windows 2000


</MENU>

1. Unordered List:
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

In an unordered list each item has the same leading symbol.


The item in the list will be rendered in the same order that they are entered.
<ul> tag is used to unordered the list.
<li> tag is used to list the items.

Syntax
1. <UL TYPE="CIRCLE"|"DISC"|"SQUARE">

TYPE defines the type of bullet used for each list item. The value can be one of the following:
CIRCLE specifies a hollow bullet.
DISC specifies a solid round bullet (Nadodi's default).
SQUARE specifies a square bullet.

Example
<ul type=‖disc‖>

<li>Item 1</li>

<li>Item 2</li>
</ul>

<ul type="square">
<li>Item 1</li>
<li>Item 2</li>
</ul>
<ul type="circle">

<li>Item 1</li>
<li>Item 2</li>
</ul>

Ordered List:
In an ordered list, each item has a seque t al leadi g symbol.
The browser assigns this seque ce automat cally.
<ol> tag is used to ordered the l st.
<li> tag is used to list the item.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
Syntax
<OL

START="value"
TYPE="A"|"a"|"I"|"i"|"1"
>
...
</OL>

START="value" indicates the starting number for the list. The number must be a positive integer.
TYPE defines the type of numbering sequence used for each list item.
The value can be one of the following:

A specifies a sequence of uppercase letters


a specifies a sequence of lowercase letters
I specifies a sequence of uppercase Roman numerals
i specifies a sequence of lowercase Roman numeral
1 specifies a sequence of numbers.

Example
<ol>

<li>Item 1</li>
<li>Item 2</li>
</ol>
<ol type="A" start="5">
<li>Item 1</li>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
<li>Item 2</li>

</ol>
<ol type="i" start="10">
<li>Item 1</li>
<li>Item 2</li>
</ol>

Definition List
A definition list is a sequence of terms and description of these terms
<dl> tag is used to implement definition list.
<dt> tag is used for defining the item.
<dd> tag is used for defining the description.

LI - (list item)
The LI tag indicates an itemized element, which is s ally preceded by a bullet, a number, or a

letter. The LI tag is used inside list elements such as OL (ordered list) nd UL ( nordered list).

A single itemized element can contain other tags such s the P t g.


The LI tag does not require a closing tag.

Syntax
<LI

TYPE="DISC"|"CIRCLE"|"SQUARE"|"A"|"a"|"I"|"i"|"1"
VALUE="number"

>
TYPE specifies the type of symbol or numbering sequence to use before each item.
DISC specifies a solid bull t.
CIRCLE specifies a hollow bull t.
· SQUARE specifi s a squa bull t.
A specifies a sequ nce of upp rcase letters.
a specifies a sequence of lowercase letters.
I specifies a sequence of uppercase Roman numerals.
i specifies a sequence of lowercase Roman numeral.
1 specifies a sequence of numbers.

The values DISC, CIRCLE, and SQUARE can be used in unordered lists, while the values A, a, I, i, and 1
can be used in ordered lists that have a numerical sequence.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
VALUE="number" indicates the starting number for an item in an ordered list. This attribute is valid
only in an ordered list. See OL for information on the types of numbering available.

Used Within DIR, DL, OL, UL, MENU

Example
<UL>
<LI>Identify items in a numbered list
<LI>Identify items in an unordered list
<LI>Identify items in a directory list

<LI>Identify items in a menu


</UL>

HTML Table:
Tables in HTML are easy to program if you know what you are trying to do.
Tables look like the charts present on many of these slides.

Tables in browsers by default have no borders, if you want to see the edges of your table, you
have to place a border command inside the table tag.
You can also use tables to format pages.

Inside tables, the text is always the default of the browser (black and small), if y u want to change
this font, you must add a <font color=―color‖ and/or size=―x‖> inside ea h ell to make the change.

TABLE
CAPTION
TR
TD
TH
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

1.14 TABLE - (table): The TABLE tag defines a table. Inside the TABLE tag, use the TR tag to define
rows in the table, use the TH tag to define row or column he dings, nd use the TD tag to define table cells.

The TABLE tag can also contain a CAPTION tag, which specifies the caption
for the table.

You can specify the width of the border surrou di g the table and the default

background color of the table. (Ind v dual rows a d cells in the table can have their own background color.)
You can use the CELLSPACING attr bute to specify the distance between cells in the table and the
CELLPADDING attribute to sp cify the distance between the border and content of every cell. If you
specify the width and height of the tabl , the browser will do its best to make the table fit the specified
dimensions, but in some cas s this may not be possible. For example, if the table contains cells that contain
non-wrapping long lin s, the table may not fit in a specified width.

Syntax
<TABLE

ALIGN="LEFT|RIGHT"
BGCOLOR="color"
BORDER="value"

CELLPADDING="value"
CELLSPACING="value"
HEIGHT="height"

WIDTH="width"
COLS="numOfCols"
HSPACE="horizMargin"
VSPACE="vertMargin"

>
...
</TABLE>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

ALIGN specifies the horizontal placement of the table.

LEFT aligns the table on the left (the default). The content following the table flows to the right
of the table.
RIGHT aligns the table on the right. The content following the table flows to the left of the table.
CENTER aligns the table in the center. Content does not flow on either side.

BGCOLOR="color"sets the color of the background for the table. This color can be verridden by a
BGCOLOR tag in the TH, TR, or TD tags.

BORDER="value" indicates the thickness, in pixels, of the border to draw ar und the table. Give the
value as an integer. A value of 0 means the table has no border. You an also supply the BORDER attribute
without specifying a value for it to indicate that the table has a border of the default thickness.

CELLPADDING="value" determines the amount of space, in pixe s, between the border of a cell and
the contents of the cell. The default is 1.

CELLSPACING="value"determines the amount of space, in pixe s, between individual cells in a table.


The default is 2.

HEIGHT="height" specifies the height of the table. The defa lt is the optimal height determined by the
contents of each cell. The height value can be a number of pixels, given as an integer, or a percentage of
the height of the page or parent element, given as an integer followed by the percent sign. The table is
scaled to fit the specified height and width.

WIDTH="width" defines the width of the table. The def ult is the optimal width determined by
the contents of each cell.

The width value can be a number of pixels, given as an integer, or a percentage of the width of the
page or parent element, given as an nteger followed by the ercent sign. The table is scaled to fit the
specified height and width.

COLS="numOfCols" indicates how ma y v rtual colum s of equal width fit in the width of the

window. Each actual column in the table occup es a virtual column. You would typically set the COLS
attribute to be equal to the numb r of columns in the table to indicate that all the columns in the table have
the same width.

If the WIDTH att ibute is suppli d, the COLS attribute indicates how many virtual columns fit in
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

the specified width If the WIDTH att ibute is not supplied, the COLS attribute indicates how many
virtual columns fit in the current window or f ame. Each column in the table occupies one of the virtual
columns. Suppose that the WIDTH attribute is "80%" and the COLS attribute is 4.

In this case, each virtual column takes up 20% of the width of the window. Each actual column in
the table occupies a virtual column, so it occupies 20% of the width of the window, so long as the table has
from 1 to 4 columns inclusive. Note, however, that if the minimum width needed to display the contents of
an actual column is greater than the width of a virtual column, then the width of the column is expanded to
fit its contents.

If the table has more actual columns than the COLS value, then the columns in excess of the COLS
value are displayed in the minimum width required to fit their contents, and the other columns divide the
remaining space equally between them.

For example, suppose the table has 4 columns, the WIDTH attribute is "80%", and the COLS value
is 3. What happens here is that the table takes up 80% of the width of the window. The fourth column uses

the minimum width necessary to display the contents of the column. The other 3 columns divide the
remaining width of the table equally between them.

HSPACE="horizMargin" specifies the distance between the left and right edges of the table and any
surrounding content.

VSPACE="vertMargin" specifies the distance between the top and bottom edges of the table and any
surrounding content.

Example 1. A Simple Table.

The following example creates a three-column, four-row table, with a yellow background. The
caption "Tables are as easy as one, two, three" is displayed at the bottom of the table.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

<TABLE BORDER CELLPADDING="8" CELLSPACING="4"


BGCOLOR=yellow>

<TR><TH> English </TH><TH> Spanish </TH><TH> German


</TH></TR>

<TR><TD> one </TD><TD> uno </TD><TD> ein </TD></TR>

<TR><TD> two </TD><TD> dos </TD><TD> zwei </TD></TR>

<TR><TD> three </TD><TD> tres </TD><TD> drei </TD></TR>


<CAPTION ALIGN="BOTTOM"> <B>Table 1</B>: Tables are as easy as
one, two, three
</CAPTION>
</TABLE>

Example 2: A More Complex Table.


The following example creates a four-column table. Each row has a different background color.

The last row contains only two cells, which both s an two rows, and the second cell spans three columns.
<TABLE CELLPADDING=3 CELLSPACING=6 BORDER=2>
<CAPTION ALIGN=TOP>
<BIG><BIG>Furniture Mart's Top Sell g Fur iture

</BIG></BIG>
</CAPTION>
<!-- heading row -->
<TR BGCOLOR=#CCCCFF>
<TH>NAME</TH>
<TH>SKU</TH>
<TH>PRICE</TH>
<TH>DESCRIPTION</TH>
</TR>
<!-- end of heading row -->
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
<!-- furniture ro s -->

<TR BGCOLOR=#DDEEAA>
<TH>Harriet Smythe Armchair</TH>

<TD>100584</TD><TD>$2150</TD><TD>description goes
here</TD> <TR>

<TR B GCOLOR=#CCFFCC>
<TH>St. Michael Sofa</TH>
<TD>100789</TD><TD>$5000</TD><TD>description goes here</TD>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

<TR>
<TR BGCOLOR=#BBDDFF>
<TH>Variety of prints</TH>
<TD>-</TD><TD>$100 to $5000</TD><TD>description goes here</TD>
<TR>

<!-- more furniture rows go here -->


<!-- last row has cells that span rows and columns -->
<TR BGCOLOR=CYAN>

<TH ALIGN=CENTER VALIGN=MIDDLE


ROWSPAN=2> <FONT SIZE=+3>JULY
SALE!!</FONT></TH>

<TD ROWSPAN=2 COLSPAN=3


ALIGN=CENTER> <FONT SIZE=+1>

Don't miss our annual July sale.


All these prices will be slashed by 50%!!!
But on Aug 1, they go back up, so don't be late!!
</FONT>

</TD>
<TR>

</TABLE>

CAPTION - (table caption)


The CAPTION tag defines a caption for a table. Pl ce the CAPTION tag within the

TABLE tag but not inside the TD or the TR tags, which indic te t ble cells and table rows respectively.

Navigator 1.1.
Syntax

<CAPTION
ALIGN="BOTTOM"|"TOP">...</CAPTION> ALIGN specifies
the placement of the caption within a table.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
BOTTOM places the caption at the bottom of the table.

TOP places the caption at the top of the table. TOP is the
default. Used Within TABLE
Example See example 1. Simple Table.

TR - (table row) The TR tag sp cifi s a table row. Use the TR tag inside a TABLE tag. The TR tag can
contain TH tags, which indicate table h adings, and TD tags, which indicate table cells.

Syntax
<TR

ALIGN="CENTER|LEFT|RIGHT"
VALIGN="BASELINE|BOTTOM|MIDDLE|TOP"

BGCOLOR="color"
>
...
</TR>
ALIGN specifies the horizontal placement of the table:
CENTER centers the table .
LEFT aligns the table to the left (the default).
RIGHT aligns the table to the right.
VALIGN specifies the vertical placement of the content in the cell:
· BASELINE aligns the content with the cell's baseline.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

BOTTOM aligns the content with the cell's bottom.


MIDDLE centers the content within the cell (the default).
TOP aligns the content with the cell's top.

BGCOLOR="color" sets the default color of the background of the table row. Table cells defined with
the TD tag inside the row can set their own background color.

Used within TABLE


Example See example 1. Simple Table.

TD - (table data)

The TD tag specifies text in a cell in a table. Use the TD tag inside a TR
tag inside a TABLE tag.

You can set the background color of a cell by specifying its BGCOLOR attribute. F r each cell,

you can use the COLSPAN and ROWSPAN attributes to specify how many lumns and r ws the cell spans.

To specify the distance between cells, set the CELLSPACING attribute in the TABLE tag. To
specify the distance between the borders of each cell and its contents, set the CELLPADDING attribute in
the TABLE tag. All cells in a table have the same padding and spacing.

If a cell is empty, that is, the <TD> tag is immediately fo owed by the </TD> tag, the space
occupied by the cell in the table is completely empty. That is, the cell has no content, no background color,
and no border. However, suppose you have a four column t ble, b t you have no data for the second
column in one of the rows. You should still provide the second TD t g for that row, because if you leave it
out the table will close the gap and move the third cell into the second column. The row will end up having
three columns only, and it will not be aligned with the rest of the t ble

If you want an empty cell to look like other cells in the table, you can give it a period or a dash to
indicate that the data is unknown, for example, <TD> - </TD>.

Syntax
<TD

ALIGN="CENTER|LEFT|RIGHT"
VALIGN="BASELINE|BOTTOM|MIDDLE|TOP"
BGCOLOR="colo "
COLSPAN="value"
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
ROWSPAN="valu "

HEIGHT="pixelHeight"
WIDTH="pixelWidth"
NOWRAP="value"
>
...
</TD>

ALIGN specifies the horizontal placement of the contents of the table cell:
CENTER centers the content within the cell.
LEFT aligns the content with the cell's left edge (the default).

RIGHT aligns the content with the cell's right edge.


VALIGN specifies the vertical placement of the contents of the
cell:
BASELINE aligns the content with the cell's baseline.
BOTTOM aligns the content with the cell's bottom.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

MIDDLE centers the content within the cell (the default).

TOP aligns the content with the cell's top.


BGCOLOR="color" sets the color of the background of the table cell.

COLSPAN="value" indicates the number of columns the cell spans. Give the number as an integer.
ROWSPAN="value" indicates the number of rows the cell spans. Give the value as an integer.
HEIGHT="pixelHeight" specifies the suggested height of the table cell, in pixels.
WIDTH="pixelWidth" specifies the suggested width of the table cell, in pixels.

NOWRAP specifies that the lines within a cell cannot be broken (that is, they do not wrap onto the next
line).

Used Within TABLE and TR


Example See example 1. Simple Table.

TH - (table heading) The TH tag specifies a table cell whose contents are usually displayed in a

bolder font than those of regular table cells. The intent of the TH tag is that you use it f r lumn r row
headings.

Syntax
<TH
ALIGN="CENTER|LEFT|RIGHT"
VALIGN="BASELINE|BOTTOM|MIDDLE|TOP"

BGCOLOR="color"
COLSPAN="value"
ROWSPAN="value"
HEIGHT="pixelHeight"
WIDTH="pixelWidth"
NOWRAP

>
...
</TH>
ALIGN specifies the horizontal placeme t of the headi g in the table cell:
CENTER centers the content w th n the cell.
LEFT aligns the cont nt with the c ll's left edge (the default).
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
RIGHT aligns the cont nt with the c ll's right edge.
VALIGN specifies the ve tical plac m nt of the contents of the cell:
BASELINE aligns the cont nt with the cell's baseline.
BOTTOM aligns the content with the cell's bottom.
MIDDLE centers the content within the cell (the default).
TOP aligns the content with the cell's top.

BGCOLOR="color" sets the color of the background of the table heading. This color can be overridden
by a BGCOLOR tag in the TD tags within the TH tag.

COLSPAN="value" indicates the number of columns the cell spans.


ROWSPAN="value" indicates the number of rows the cell spans.
HEIGHT="pixelHeight" specifies the suggested height of the table cell, in pixels.
WIDTH="pixelWidth"specifies the suggested width of the table cell, in pixels.
NOWRAP specifies that the lines within a cell cannot be broken; that is, they do not
wrap onto the next line.

Table's Attributes
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

border (example)

This specifies the width in pixels of the border around the table
This is in addition to the border around each cell (the "cellspacing").

The default is zero


cellspacing (example)
This gives the space in pixels between adjacent cells.

The default is usually about 3


cellpadding (example)

Specifies the space between the cell walls and


contents The default is usually about 1

width
This specifies the width of the table
In pixels (<table width="250">), or

As a percentage of the current browser window width


(<table width="75%">)

rules (example) Specifies the horizontal/vertical divider lines.


Must be used in conjunction with the "border"
attribute!
frame (example) Specifies which outer borders are drawn.All fo r are drawn if this attribute is omitted.

Table Row (tr) Define each row in the table


Each row may contain table header (th) and table d ta (td) elements

Attributes:
align: Horizontal alignment
Values: "left", "center", "right", "justify", "ch r"
valign: Vertical alignme t
Values: "top", "m ddle", "bottom"
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
Table Header (th) and Table Data (td)
Define a table cell

Attributes

Colspan: Defines a h ading or c ll data entry that spans multiple columns


Rrowspan:Defines a h ading or c ll data entry that spans multiple rows
align: "left", " ight", "c nt ", "justify", "char"

e.g :, the following aligns ntries on a decimal point


<td align="cha " cha =".">…</td>
valign:"top", "bottom", "middle"
width, height: Cell idth and height in pixels only (no percentages officially allowed)

HTML Frames:

Frames and Framesets

This section discusses the tags for creating frames and frame sets. A frame is region of a window
that acts as a indow itself. The main window can contain multiple frames, so that different regions of the

indow display different contents. A frame set is a set of frames.

FRAME
FRAMESET
NOFRAMES
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

FRAME - (window region)

The FRAME tag creates a frame, which is an individual, independently scrollable region of a web
browser. You can think of it as a window within a window. The FRAME tag must be used within a
FRAMESET tag.

The FRAMESET tag contains a set of FRAME tags, which each define a frame in the main
window.

Each frame has a distinct URL that determines the content displayed by the frame.

You can specify whether or not a frame has a border, whether or not it has margins, whether or not
the user can resize it dynamically, and whether or not it is scrollable.

Syntax
<FRAME

BORDERCOLOR="color"
FRAMEBORDER="YES"|"NO"

MARGINHEIGHT="marginHeight"
MARGINWIDTH="marginWidth"

NAME="frameName"
NORESIZE
SCROLLING="YES"|"NO"|"AUTO"
SRC="URL"
>

The URL tag is required.

BORDERCOLOR="color" specifies the color of the fr me's borders. Because frames share borders,
Navigator must resolve any border color conflicts.

FRAMEBORDER determines whether or not the frame has visible borders.


YES results in an outline-3D border.
NO suppresses the 3D border.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
When the FRAMEBORDER attr bute appears in a FRAMESET tag, it sets a default
FRAMEBORDER value for all frames the frameset. When the FRAMEBORDER attribute appears in the
FRAME tag, it applies only to that part cular frame, overriding any FRAMEBORDER attribute established
by an outer FRAMESET tag. A border shared between frames is plain only if all adjacent frames have the
FRAMEBORDER att ibute s t to NO.

When neither a FRAME nor a FRAMESET tag governing that FRAME has set
the FRAMEBORDER att ibut , the d fault s tting is YES.

MARGINHEIGHT="ma ginHeight" specifies a margin, in pixels, between the top and bottom edges of
the frame and the frame contents

MARGINWIDTH="marginWidth" specifies a margin, in pixels, between the left and right edges of the
frame and the frame contents.

NAME="frameName" specifies the name of the frame. The value of the NAME attribute must begin ith
an alphanumeric character.

NORESIZE specifies that users cannot resize the frame. If a frame adjacent to an edge is not resizable, the
entire edge is not resizable, and consequently other frames adjacent to that edge are not resizable.

SCROLLING specifies whether scrollbars are available on a frame:


YES specifies that scrollbars are always available.
NO specifies that scrollbars are never available.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

AUTO specifies that the browser determines whether to display scroll bars based on the
size of the frame and its content. If you do not specify a value for SCROLLING, the default value
is AUTO.

SRC="URL" specifies the URL for the document to be displayed in the frame. The URL cannot include
an anchor name; for example FRAME SRC="doc2.html#colors" is invalid. If you do not specify the SRC
attribute, the frame is displayed with no content

Used Within FRAMESET


Example See Framest example 1. Simple Frameset with two frames.

FRAMESET - (set of frames)


The FRAMESET tag defines a set of frames that appear in a web browser wind w.

The FRAMESET tag contains one or more FRAME tags that each describe a frame.

The only place the FRAMESET tag can be used is in a frame definition d cument, which is an
HTML document that contains the FRAMESET and FRAME tags that des ribe the framesets and frames
that make up a Navigator window.

An HTML document that contains a FRAMESET tag cannot contain a BODY tag.

A frameset can specify that its frames are laid out in rows or co umns If youwant your frameset to
have rows and columns, rather than just rows or columns, you can se FRAMESET tags nested inside
FRAMESET tags.

For example, you could define a frameset that has two col mns, where the first column contains a
frameset that has two rows and the second column cont ins fr meset th t has 4 rows.

You can specify the border thickness for all frames in top-level fr meset. You can also specify whether

or not all frames in a set display their border by default nd wh t color the border uses. Individual frames in
the set can override the default to specify whether or not they displ y their border, and what color their
border uses.

You can specify actions to occur when the wi dow dis laying the frameset gets or loses focus, and
you can specify actions to occur when the frameset s loaded or unloaded.

When you define a link, (using the <A HREF> tag) you can specify in which frame the destination
document is displayed, by giving the name of the frame as the value of the link's TARGET attribute. It is
possible to define a link to change the content of multiple frames in one go by using the ONCLICK
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
attribute of the link. To do this, s t the value of the link's ONCLICK attribute to JavaScript code that
changes the location (sou c ) of one or more frames.

For example, the file f am s t.htm op ns a web page that has three frames. If you click a link in the
left frame, both the other f am s update. You can open the file framtoc.htm and view its source to see the
code for the links that update multiple frames.

The NOFRAMES tag is used inside a FRAMESET tag to provides alternative content for browsers
that cannot display frames

Syntax
<FRAMESET

COLS="columnWidthList"
ROWS="ro HeightList"

BORDER="pixWidth"
BORDERCOLOR="color"

FRAMEBORDER="YES"|"NO"
ONBLUR="JScode"
ONFOCUS="JScode"
ONLOAD="JScode"
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

ONUNLOAD="JScode"

>
...
</FRAMESET>
You must supply at least one of the COLS or ROWS attribues.

COLS="columnWidthList" specifies a comma-separated list of values giving the width of each frame in
the frameset. If one of the values is missing, the browser sizes the corresponding frame to fit the space
available.

The browser may approximate some values to make the total width of the colu ns equal to the
width of the window.

The value of each item in the columnWidthList can be one of the following:
Width of a frame in pixels.
Width of a frame as a percentage of its parent frame or window.

An asterisk (*), which means "as much space as possible," whi h is the space left over
after space has been allocated to all columns that specify their width as pixel value or a percentage

value . The total available left-over space is divided equa y between a l olumns that use an asterisk.

ROWS="rowHeightList" specifies a comma-separated list of val es giving the height of each frame in
the frameset. If one of the values is missing, the corresponding fr me is sized to fit the space available. The
browser may approximate some values to make the tot l height of the rows equal to the height of the
window. Each item in rowHeightList can be one of the following:

· Height of a frame in pixels.


· Height of a frame as a perce tage of the arent frame or window.

An asterisk (*) which mea s "as much s ace as possible," which is the space left over after
space has been allocated to all rows that specify their height as pixel value or a percentage value .
The total available left-over space s divided equally between all rows that use an asterisk.

BORDER="pixWidth" sp cifi s the thickn ss of frame borders for all frames in an outermost frameset. A
setting of 0 causes all f am s in the fram set to have no border between them. A setting of 3 causes a border
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
of 3 pixels If no BORDER tag is pr sent,the default is 5 pixels. The BORDER tag can be used only on an
outermost FRAMESET tag.

BORDERCOLOR="colo " specifies the color of a frame's borders. Because frame borders are shared,
Navigator must resolve any border color conflicts.

Any BORDERCOLOR attribute appearing in the outermost FRAMESET has the lowest priority.
This attribute is overridden by any attribute used in a nested FRAMESET tag.

Finally, any BORDERCOLOR attribute in the current FRAME tag overrides all previous
FRAMESET tag settings. If there is a conflict for two colors of equal priority both set on the same edge,
the behavior is undefined.
FRAMEBORDER determines how frame borders are displayed.
YES results in an outline-3D border.
NO suppresses the 3D border.

When the FRAMEBORDER attribute appears in the FRAMESET tag, it sets a default
FRAMEBORDER value for all frames in that frameset. When the FRAMEBORDER attribute appears in a
FRAME tag, it applies only to that particular frame, overriding any FRAMEBORDER attribute specified
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

by an outer FRAMESET tag. A border shared between frames is plain only if all adjacent frames have the
FRAMEBORDER attribute set to NO. When neither a FRAME nor a FRAMESET tag governing that
FRAME has set the FRAMEBORDER attribute, the default setting is YES.

ONBLUR="JScode" specifies JavaScript code to execute when the window containing the frameset loses
focus.

ONFOCUS="JScode" specifies JavaScript code to execute when the window containing the frameset
gets focus.

ONLOAD="JScode" specifies JavaScript code to execute when the frameset is loaded into
the frame.

ONUNLOAD="JScode" specifies JavaScript code to execute when the frameset is unloaded (exited).

Frameset Example 1. Simple Frameset With Two Frames

The following example creates a set of two frames. The frameset is kept in a d cument file, such as
index.html, that contains no other information. When users open this page in their web br wser, the
FRAMESET tag loads the individual URLS referenced in the FRAME tags

<HTML>

<HEAD> <TITLE>Simple Frame Set


Example</TITLE></HEAD> <FRAMESET COLS="20%,80%"
BORDER=10> <FRAME SRC="simpltoc.htm"
NAME="exampletoc">

<FRAME SRC="forms.htm" NAME="examplecontent">


<NOFRAMES>You must use a browser that c n displ y fr mes
to see this page. </NOFRAMES> </FRAMESET>

</HTML>

The two frames appear as columns because COLS is s ecified within the FRAMESET tag. The left frame
uses 30% of the available space, and the r ght frame uses the remaining 70% of the space. By default, the
frames in this example have scrollbars a d are resizable, because no values are specified for the
SCROLLING and NORESIZE attributes.

Example 2: Nested Fram s

The following example c at s a frameset that contains a nested frameset. Theoutermost frameset has
two columns. The second column contains a nested frameset that has two rows.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

<HTML><HEAD><TITLE>F ame Set Example</TITLE></HEAD>


<FRAMESET COLS="20%,*">

<NOFRAME>You must use a browser that can display


frames to see this page.</NOFRAME>

<FRAME SRC="frametoc.htm" NAME="noname">


<FRAMESET ROWS="30%,*">
<FRAME SRC="frtoc1.htm" NAME="toptoc">
<FRAME SRC="frstart.htm" NAME="outer">

</FRAMESET>

</FRAMESET>
</HTML>

NOFRAMES - (alternative text for frames)


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

The NOFRAMES tag specifies content that is displayed by browsers that do not know how to display
frames. Browsers that can display frames ignore all text in the NOFRAMES tags unless a file called by a
frame tag is missing or unreachable by the browser. Place the NOFRAMES tag within the FRAMESET
tag.

Syntax
<NOFRAMES>...</NOFRAMES>

Used Within <FRAMESET>

HTML Forms:

Form is a layout component used in web page to interact the user.


Form is also used to link the another page or another form based on the action .
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

List of component

Text Text
Area
Label
Button
Check box
Radio button
Menus
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

1. Text
Text component is used to insert a text in web page.
<Input> tag is used to insert a text component in document.
General form
<input type=‖text‖ size=25 value= ― ―>
Text Area
Text Area component is used to feed multiple line of text.
Attribute in text area component.
Row: Row attribute used to denote the total number of rows in the text area.
Column: Column attribute is used to denote the number of column in the text area.
Name: Name attribute is used to denote the name of the text area.
Wrap: Wrap attribute is used to wrap the text inside the text area
<text area> tag is used to insert the text area in the web document
General form:
o <text area cols=‖value‖ rows=‖values‖ >----</text area>
• Example:
o <text area cols=‖50‖ rows=‖40‖ name=‖name‖>---</text area>
Label
Label tag is used to create text box to fill the text.
This tag has starting tag (<label>) and ending t g (</l bel>).
Example
o<label> Name <input type=text size=40>--</label>

Check box
Check box component is used to place the checkbox in the web document.
General form:
o<input type=checkbox> ----- </ put>

MENU - (list of simple it ms)


The MENU tag displays a list of simple items. This tag works just like the UL tag.

Use the LI tag to d signate the individual menu items.


This tag is being dep cat d b cause it has become obsolete in favor of the UL tag.

Syntax
<MENU>

...
</MENU>

Example
The follo ing example creates a list of three short items:
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
<P>HTML Menu Example:</P>

<MENU>
<LI> Windows 9x

<LI> Windows NT
<LI> Windows 2000
</MENU>

Forms

This section discusses the tags for creating forms.

FORM
INPUT

INPUT TYPE="BUTTON"
INPUT TYPE="CHECKBOX"

INPUT TYPE="FILE"
INPUT TYPE="HIDDEN"
INPUT TYPE="IMAGE"

INPUT TYPE="PASSWORD"
INPUT TYPE="RADIO"
INPUT TYPE="RESET"
INPUT TYPE="SUBMIT"
INPUT TYPE="TEXT"
SELECT
OPTION
ISINDEX

FORM - (form for user input)

The FORM tag creates an HTML form. The form can contain interface e ements such as text fields,
buttons, checkboxes, radio buttons, and selection lists that let sers enter text and make choices. Each
interface element in the form must be defined with n ppropri te tag, such as <INPUT> or <SELECTION>.
All elements in the form must be defined between the <FORM> and </FORM> tags. As well as user input
elements, the form can contain other elements such s headings, paragraphs, tables, and so on.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

When the form is displayed in a web browser, the user can fill it out by making choices and
entering text using the interface elements, a d then submit the form by clicking a "Submit" button.

Kinds of Interface Elements

Several kinds of form elements can be def ed usi g the INPUT tag, which uses the TYPE attribute
to indicate the type of elem nt, such as button, checkbox, and so on.

Two other kinds of int rface l m nts you can put in a form are selection lists and text areas.
Selection lists act as menus and a d fin d with the SELECT tag. Multi-line text-entry fields are defined
with the TEXTAREA tag

Submit Buttons and CGI P og ams

To enable the form to process the data that the user enters, it must have a "Submit" button, which is
a button defined by an <INPUT TYPE="SUBMIT"> or an <INPUT TYPE="IMAGE"> tag.

The action invoked hen the user clicks a "Submit" button is defined by the ACTION attribute of the
FORM tag. The value of the ACTION attribute is usually a URL that points to a CGI program. A CGI
program runs on a server, processes arguments sent by the form, and returns data to the browser.

The value of the form's METHOD attribute also affects the way the CGI program is invoked. It is
beyond the scope of this reference to provide details of CGI programming, but many fine books are
available on the subject, and also lots of information is available on the web.

ONCLICK and ONSUBMIT

You can also define OnClick event handlers for several kinds of input elements. An OnClick event
handler is a piece of JavaScript code that is executed when the element is clicked.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

executes when a "Submit" button in the form is pressed. If the JavaScript code returns false, the form's
action ends there, and the URL specified by the ACTION attribute is not invoked.

If the JavaScript code returns anything else, the URL specified by the ACTION attribute is
invoked. For example, you could use the ONSUBMIT attribute to check whether or not the user really
wants to submit the form.

Name/Value Pairs
When a form is submitted, the data contained in the form is sent to the invoked CGI program as a

series of name/value pairs. The name portion of each pair is the name of an interface ele ent as specified
by its NAME attribute. In most cases the value portion is the value displayed by the ele ent, f r exa ple,
the text displayed in a text field.

Nesting Forms

A document can have multiple forms, but forms cannot be nested -- you ann t have a f rm within a
form. If your document uses positioned HTML content, each form must be ompletely ntained within one
positioned block.

Syntax
<FORM

ACTION="serverURL"

ENCTYPE="encodingType"
METHOD="GET"|"POST"
NAME="formName"
ONRESET="JScode"
ONSUBMIT="JScode"
TARGET="windowName"

>
...
</FORM>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

The FORM tag has an optional ONSUBMIT attribute, whose value is a JavaScript event handler that

The ACTION attribute is required if any act on s to occur when the user presses a "Submit" button in the
form.

ACTION="serverURL" sp cifi s the URL of the program to be invoked when the form is submitted.
The action can also be a mailto: URL if the form results are to be mailed to someone.
ENCTYPE="encodingTyp " sp cifi s the MIME encoding of the data sent:

"application/x-www-fo m-u l ncod d" (the default), is usually used if the METHOD attribute has
the value POST.

"multipart/form-data" is used when the form contains a file upload element (INPUT
TYPE="FILE").

METHOD specifies how information is sent to program invoked by submitting the form.

GET (the default) appends the input information to the URL which on most receiving systems
becomes the value of the environment variable QUERY_STRING.

POST sends the input information in a data body that is available on stdin with the data length set
in the environment variable CONTENT_LENGTH.

NAME="formName" specifies the name of the form. The name is not displayed on the form.

JavaScript can use the NAME attribute to differentiate different forms if there are multiple forms on a
page.

ONRESET="JScode" specifies JavaScript code that executes when a user resets the form by using a
RESET button.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

ONSUBMIT="JScode" specifies JavaScript code that executes when a user submits the form by clicking
a "Submit" button.You can use the ONSUBMIT attribute to prevent a form from being submitted; to do
so, put a return statement that returns false in the JavaScript code. Any other returned value lets the form
submit. If you omit the return statement, the form is submitted.

TARGET="windowName" specifies the window that displays the data returned by the invoked program.

Example

The following example creates a form called LoginForm that contains text fields for user name and
password, a submit button, and a cancel button.

<FORM NAME="LoginForm" METHOD=POST ACTION="urltoInvoke">


<P>User name:

<INPUT TYPE="text" NAME="userName"


SIZE="10"> <P>Password:

<INPUT TYPE="password" NAME="password"


SIZE="12"> <P><INPUT TYPE="submit" VALUE="Log
in">

<INPUT TYPE="button" VALUE="Cancel" onClick="window c ose()">


</FORM>

INPUT - (input element in a form)

The INPUT tag defines a form element that can receive ser input. The TYPE attribute
determines the specific sort of form element to be created. TYPE can be one of the
following:

BUTTON places a button on an HTML form. Use J v Script code to make the button
perform an action you define.
CHECKBOX places a toggle switch on an HTML form, letting the user set a value on or
off.
FILE places an element on an HTML form letting the user supply a file as input. When the
form is submitted, the co te t of the specified file is sent to the server along with the other
form data.
HIDDEN specifies an nv s ble text element. A hidden element is used for passing
information to the s rv r wh n a form is submitted.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

IMAGE plac s an imag , s rving as a custom button, on an HTML form. When a user clicks
an image l m nt, the form is submitted to the server.
PASSWORD plac s a t xt input field on an HTML form. Each character typed in the field is
displayed as a cha acter such as * or a black dot to conceal the actual value.
RADIO places a radio button on an HTML form. Radio buttons can be grouped into sets,
and only one button per set can be selected at a time.
RESET places a reset button on an HTML form. When a user clicks a reset button, all
elements in the form are reset to their default values.

SUBMIT places a submit button on an HTML form. When a user presses a submit button,
the form is submitted.
TEXT places a single line text input field on an HTML form. A text field lets the user enter
text.

INPUT TYPE="BUTTON"

A button apears in the form. You must specify JavaScript code as the value of the ONCLICK
attribute to determine what happens when the user clicks the
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

button.

Syntax
<INPUT TYPE="BUTTON"
NAME="buttonName"

VALUE="buttonText"
ONCLICK="JScode"
>

NAME="buttonName" specifies the name of the button. The name does not appear in the form.
VALUE="buttonText" specifies the text to be displayed in the button.
ONCLICK="JScode" specifies JavaScript code to execute when a user clicks the butt n.

Example
<FORM METHOD=POST ACTION="/cgi-bin/example.cgi">

<INPUT TYPE="button" VALUE="Close Window"


onClick="window.close();">

</FORM>

INPUT TYPE="CHECKBOX" A checkbox is a toggle that the ser can se ect (switch on) or deselect
(switch off.)

Syntax
<INPUT TYPE="CHECKBOX"

CHECKED
NAME="name"

ONCLICK="JScode"
VALUE="checkboxValue"
>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

CHECKED indicates that the checkbox s d splayed with a tick mark to indicate that it is
selected.

NAME="name" specifies the name of the input element. This value is the name portion of the
name/value pair for this el m nt that is s nt to the server when the form is submitted. The name is not
displayed on the form

ONCLICK="JScode" sp cifi s JavaScript code to execute when a user clicks the checkbox.
VALUE="checkboxValue" specifies the value to be returned to the server if the checkbox is selected
when the form is submitted The default value is ON, but you can specify a different value if you want.
When the form is submitted, only the name/value pairs for selected checkboxes are sent to the invoked
CGI program.

Example

<P>Specify your music preferences (check all that apply):</P>


<BR><INPUT TYPE="checkbox" NAME="musicpref_rnb" CHECKED>
R&B

<BR><INPUT TYPE="checkbox" NAME="musicpref_jazz"


CHECKED> Jazz

<BR><INPUT TYPE="checkbox" NAME="musicpref_blues"


CHECKED> Blues
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

<BR><INPUT TYPE="checkbox" NAME="musicpref_newage"


CHECKED> New Age

INPUT TYPE="FILE" This places an element on an HTML form that lets the user supply a file as input.
When the form is submitted, the content of the specified file is sent to the server as the value portion of the
name/value pair for this input element.

If a form contains a file input element, the value of the ENCTYPE attribute of the FORM tag
should be "multipart/form-data".

Syntax
<INPUT TYPE="FILE"

NAME="name"
VALUE="filename"
>

NAME=name specifies the name of the input element. This value is used as the name p rti n f the
name/value pair for this element that is sent to the server when the form is submitted. The name is not
displayed on the form.

VALUE=filename specifies the initial value of the input element.

Example
<FORM ENCTYPE="multipart/form-data"

ACTION="/cgi-bin/example.cgi" METHOD="POST">

<P>File name:
<INPUT TYPE="file">
</FORM>

INPUT TYPE="HIDDEN"

A hidden input element is an invisible element whose main purpose is to contain data that the user
does not enter. This data gets sent to the i voked CGI rogram when the form is submitted.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
This tag provides a mechanism for del ver g a value to the CGI program without the user having
entered it, but note that it is not very h dden because the user can discover it by viewing the document
source.

Syntax
<INPUT TYPE="HIDDEN"

NAME="name"

VALUE="value"
>

NAME="name" specifies the name of the input element. This value is the name portion of the
name/value pair sent to the invoked CGI program when the form is submitted. The name is not displayed
on the form.

VALUE="value" specifies the initial value of the input element.

Example

This example creates a form with a hidden element, DefaultPass, that stores the initial value of the
pass ord field.

<FORM NAME="LoginForm" METHOD=POST ACTION="/cgibin/

example.cgi">

<P>Password:
<INPUT TYPE="password" NAME="password" SIZE="12"
VALUE="treasure">
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

<INPUT TYPE="hidden" NAME="DefaultPass" VALUE="treasure">


</FORM>

INPUT TYPE="IMAGE"

This places an image, serving as a custom button, on an HTML form. When a user clicks the
image, the form is submitted to the server.

Syntax
<INPUT TYPE="IMAGE"

ALIGN="LEFT"|"RIGHT"|"TOP"|"ABSMIDDLE"|"ABSBOTTOM"|
"TEXTTOP"|"MIDDLE"|"BASELINE"|"BOTTOM"
NAME="name"

SRC="location"
>

ALIGN specifies the alignment of the image in relation to the surrounding text. If y u do n t specify a
value for ALIGN, Navigator uses BOTTOM as the default. The possible values are LEFT, RIGHT, TOP,
ABSMIDDLE, ABSBOTTOM, TEXTTOP, MIDDLE, BASELINE, and BOTTOM. See the section
"IMG" for a description of the values.

NAME=name specifies the name of the input element. This value is used as the name portion

of the name/value pair for this element that is sent to the invoked CGI program when the form is
submitted. The name is not displayed on the form.When Navigator sends the offsets of the image to the
server, it sends them as name.x and name.y.

SRC="location" specifies the URL of the image to be displ yed in the doc ment.

Example
<CENTER><INPUT TYPE="image" SRC="signnow.gif"></CENTER>

INPUT TYPE="PASSWORD" A password element is a text in ut field in which each character typed is
displayed as a character such as * or a black dot to co ceal the actual value.

Syntax
<INPUT TYPE="PASSWORD"
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

MAXLENGTH="maxChar"

NAME="name"
ONSELECT="JScod "
SIZE="charLength"
VALUE="textValu "
>

MAXLENGTH="maxCha " specifies the maximum number of characters a password box can accept.
NAME="name" specifies the name of the input element. This value is used as the name portion

of thename/value pair for this element that is sent to the server when the form
is submitted. The name is not displayed on the form.

ONSELECT="JScode” specifies JavaScript code to execute when a user selects some of the text in the
text element.

SIZE="charLength" specifies the length of the input field, in characters. The value should be an integer.
VALUE="textValue"specifies the initial value of the password, if any.

Example
<P>Password:

<INPUT TYPE="password" NAME="password" VALUE="" SIZE="25">


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

INPUT TYPE="RADIO" A radio element is a radio button. A set of radio buttons consists of multiple
radio buttons that all have the same NAME attribute. Only one radio button in the set can be selected at
one time. When the user selects a button in the set, all other buttons in the set are deselected. If one radio
button in a set has the CHECKED attribute, that one is selected when the set is first laid out on the
window.

Syntax
<INPUT TYPE="RADIO"

CHECKED
NAME="name"
ONCLICK="JScode"

VALUE="buttonValue"
>
CHECKED indicates that the radio button is selected.
NAME="name" specifies the name of the input element. This value is used as the name p rti n

of the name/value pair for this element that is sent to the invoked CGI program when the f rm is submitted.
The name is not displayed on the form. All radio buttons that have the same name constitute a radio group;
only one radio button of a group can be set at one time.

ONCLICK="JScode" specifies JavaScript code to execute when a ser c icks the radio button.
VALUE="value” specifies the value that is returned to the server when the radio button is selected and
the form is submitted. Only name/value pairs for radio buttons that are selected are sent to the invoked
CGI program. The value defaults to ON.

Example
The following example creates a radio button group.

<P>Category:

<BR><INPUT TYPE="radio" NAME="category" VALUE="liv" CHECKED>


Living

<BR><INPUT TYPE="rad o" NAME="category" VALUE="din"> Dining


<BR><INPUT TYPE="rad o" NAME="category" VALUE="bed">
Bedroom
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
INPUT TYPE="RESET" When a user presses a reset button, all elements in the form are reset to their
default values

Syntax
<INPUT TYPE="RESET"

NAME="name"
ONCLICK="JScode"
VALUE="label"
>
NAME="name"specifies the name of the input element.
ONCLICK="JScode" specifies JavaScript code to execute when a user clicks the button.
VALUE="label" specifies the text to display on the face of the reset button.

Example

This example displays a text element with the default value CA and a reset button labelled Clear
Form. If the user types a state abbreviation in the text element and then clicks the Clear Form button, the
original value of CA is restored.

<FORM>
<P>State: <INPUT TYPE="text" NAME="state" VALUE="CA" SIZE="2">
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

<P><INPUT TYPE="reset" VALUE="Clear Form">

</FORM>

INPUT TYPE="SUBMIT" When a user clicks a submit button, the form is submitted, which means that
the ACTION specified for the form is invoked.

Syntax
<INPUT TYPE="SUBMIT"

NAME="name"
VALUE="label">
NAME="name" specifies the name of the input element. The name is not displayed on the form.
VALUE="label" specifies the text to display on the face of the submit button.

Example
<INPUT TYPE="submit" NAME="SubmitButton" VALUE="Done">

INPUT TYPE="TEXT" A text element is a single line text input field in whi h the user an enter text.

Syntax
<INPUT TYPE="TEXT"

MAXLENGTH="maxChars"
NAME="name"
ONBLUR="Scode"
ONCHANGE="JScode"
ONFOCUS="Scode"
ONSELECT="JScode"

SIZE="lengthChars"
VALUE="text"
>
MAXLENGTH="maxChars" specifies the maximum umber of characters a text box can accept.
NAME="name" specifies the name of the put eleme t. This value is used as the name portion
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
of the name/value pair for this eleme t that s se t to the invoked CGI program when the form is

submitted. The name is not displayed on the form.

ONBLUR="JScode" specifies JavaScr pt code to execute when the text element loses keyboard
focus.

ONCHANGE="JScode" sp cifi s JavaScript code to execute when the text element loses focus and its
value has been modified

ONFOCUS="JScode" sp cifi s JavaScript code to execute when a user clicks the text element. See the
JavaScript Guide forSee the JavaSc ipt Guide for more information.

ONSELECT="JScode" specifies JavaScript code to execute when a user selects some of the text in the
text element.

SIZE="lengthChars" specifies the length of the input field, in characters.


VALUE="text" specifies the initial value of the text element.

Example
<P>Last name:

<INPUT TYPE="text" NAME="last_name" VALUE="" SIZE="25">

SELECT - (selection list in a form)

The SELECT tag defines a selection list on an HTML form. A selection list displays a list of
options from which the user can select an item. If the MUTLIPLE attribute is supplied, users can select
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

multiple options from the list at a time. If the MULTIPLE attribute is not supplied users can select only
one option in the list at a time.

The SIZE attribute specifies how many options in the list are displayed at one time. For multiple-
selection lists, if you do not specify the SIZE attribute, the browser displays some, maybe all, of the
options. For single-selection lists, by default Navigator displays the list as a drop-down menu that initially
shows only one option. The user can click the list to display the rest of the options. If you specify the SIZE
attribute, the list is displayed as a scrolling list that shows the specified number of options, regardless of

whether the list allows single or


multiple selection..

The SELECT tag should be used between <FORM> and </FORM> tags. Use the OPTION tag to
define options in the list. When the form containing the selection list is submitted to the server, a
name/value pair is sent for each selected option in the list.

Syntax
<SELECT

NAME="selectName"

MULTIPLE

ONBLUR="JScode"
ONCHANGE="JScode"
ONCLICK="JScode"
ONFOCUS="fScode"
SIZE="listLength"
>
<OPTION...>
...
<OPTION ...>
</SELECT>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
MULTIPLE specifies that multiple tems can be selected. If this attribute is omitted, only one item can be
selected from the list. If multiple select on s enabled, the user usually needs to hold down the Shift key to
select additional items.

NAME="selectName" sp cifi s the name of the select element. This value is the name portion of the
name/value pair sent to the invok d CGI program when the form is submitted. The name is not displayed
on the form.

ONBLUR="blurJScode specifies JavaScript code to execute when the select element loses focus.
ONCHANGE="changeJScode" specifies JavaScript code to execute when the select element loses focus
and its value has been modified

ONCLICK="JScode" specifies JavaScript code to execute when a user clicks an item in the list.
ONFOCUS="focusJScode" specifies JavaScript code to execute when the element gets focus.
SIZE="ListLength" specifies the number of options visible when the form is displayed. If the list
contains more options than specified by size, the list is displayed with scrollbars.

Used WithinFORM

Select Example 1:Single Item Selection


<FORM>
<B>Shipping method:</B><BR>
<SELECT>
<OPTION> Standard
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

<OPTION SELECTED> 2-day

<OPTION> Overnight
</SELECT>
</FORM>

Example 2: Multiple Selection


<FORM>

...

<B>Music types for your free CDs:</B><BR>


<SELECT NAME="music_type_multi" MULTIPLE>
<OPTION> R&B
<OPTION> Jazz
<OPTION> Blues
<OPTION> Reggae

</SELECT>
</FORM>

Example 3: Multiple Selection With Default

In the following example, all seven options can be chosen, b t bananas are selected by default. The
list is displayed as a scrollable menu that fits four options at a time.

<FORM>

<SELECT NAME="fruit choices" MULTIPLE>

<OPTION>Apples
<OPTION SELECTED>Bananas
<OPTION>Cherries
<OPTION>Oranges
<OPTION>Pineapple
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
<OPTION>Figs

<OPTION>Guava
</SELECT>
</FORM>

OPTION - (option in a SELECT list) The OPTION tag specifies an option in a selection list. Use the
OPTION tag inside a SELECTION tag. Wh n the form containing the selection list is submitted to the
server, a name/value pair is sent for each selected option in the list. The value portion of an option is the
value of the VALUE attribute, if it has one, otherwise, it is the text that follows the <OPTION> tag.

Syntax
<OPTION

VALUE="optionValue"
SELECTED
>
...

</OPTION>

VALUE="OptionValue" specifies a value that is returned to the server when the option is selected and
the form is submitted. When no VALUE attribute is present, the value returned is the same as the text
following the <OPTION> tag.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

SELECTED specifies that the option is selected by default.

Used within FOR


Example See example 1:Single Item Selection.

ISINDEX - (searchable index)

The ISINDEX tag causes the web page to display a text entry field in which the user can type a
string. The intent of this tag is that it "switches on searching" in the page, but in reality, this tag is useful
only if the page is generated by a CGI program.

The intent is that when the user enters text into the text entry field and presses the Return key (or
clicks an appropriate button on the browser), the CGI program is invoked again, with the argu ents
generated from the data in the text field. The browser outputs a new page whose c ntent is deter ined by
what the user entered in the text field.

The CGI program should test for the presence of arguments. If there are n ne, it sh uld display a
default page that includes the ISINDEX tag in the header. If there are arguments, the s ript does whatever
it needs to do. The string entered by the user is the first argument, and the anguage your script uses
determines how you access the first argument.

It is beyond the scope of this reference to provide details on CGI programming, but many fine
books are available on the subject, and lots of information is v il ble on the web.

Note that ISINDEX does not require a closing t g.

Syntax
<ISINDEX PROMPT="text" >

PROMPT="text" specifies the text that appears as the search prompt in the browser.

Used Within HEAD

Example
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

The following snipp t of code from a CGI program generates the header for an HTML page. When
the page is displayed, it has a text ent y field whose prompt is "Enter a search keyword:".

cat << EOF


<HEAD>
<ISINDEX PROMPT="Enter a search keyword:">
</HEAD>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

UNIT III CLIENT-SIDE PROCESSING AND SCRIPTING

JavaScript Introduction – Variables and Data Types-Statements – Operators - Literals-Functions- Objects-


Debuggers.

Client Side Programming : JavaScript

JavaScript was designed to add interactivity to HTML pages


JavaScript is a scripting language
A scripting language is a lightweight programming language
JavaScript is usually embedded directly into HTML pages
JavaScript is an interpreted language (means that scripts execute without preliminary compilation)

What can a JavaScript do?

JavaScript can put dynamic text into an HTML page

JavaScript can react to events - A JavaScript can be set to execute when something happens, like
when a page has finished loading or when a user clicks on an HTML element

JavaScript can read and write HTML elements - A JavaScript can read and hange the ontent
of an HTML element

JavaScript can be used to validate data - A JavaScript can be used to va idate form data
before it is submitted to a server. This saves the server from extra processing

JavaScript can be used to create cookies - A JavaScript can be sed to store and retrieve
information on the visitor's computer

The Real Name is ECMAScript. JavaScript is an implement tion of the ECMAScript lang age
standard.ECMAScript is developed and maintained by the ECMA org niz tion. ECMA-262 is the
official JavaScript standard. The language was invented by Brendan Eich at Netsc e (with N vig
tor 2.0), and has appeared in all Netscape and Microsoft browsers since 1996. The develo ment of
ECMA-262 st rted in 1996, and the first edition of was adopted by the ECMA General Assembly
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Structure of Java Script

<html>

<head>

<script type="text/javascript">

document.writeln(“H lo World!);
------

</script>

</head>

<body>

----

----

</body>

</html>

To insert a JavaScript into an HTML page, we use the <script> tag. Inside the <script> tag
we use the type attribute to define the scripting language.

So, the <script type="text/javascript"> and </script> tells where the JavaScript starts and
ends. It is possible to have script code inside the body tag also as shown below. If it is
placed inside the body tag, the script will be executed

hen the content of HTML document is displayed.

<html>

<body>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
<script type="text/javascript">

............

</script>

</body>

</html>

The document.write command is a standard JavaScript command for writing output to a


page. By entering the document.write command between the <script> and </script> tags,
the browser will recognize it as a JavaScript command and execute the code line. In this
case the browser will write Hello World! to the page:

Scripts in <head>

Scripts to be executed when they are called, or when an event is triggered, are p aced in fun
tions It is a good practice to put all your functions in the head section, this way they are all in
one place and do not interfere with page ontent.

Example

<html>

<head>

<script type="text/javascript">
function message()

alert("This alert box was called with the o load eve t");

</script>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
</head>

<body onload="message()">

</body>

</html>

JavaScripts in a page will be x cut d imm diat ly while the page loads into the browser. This
is not always what we want. Sometimes we want to x cute a sc ipt wh n a page loads, or at a
later event, such as when a user clicks a button. When this is the case we put the script
inside a function

Scripts in <head> and <body>

You can place an unlimited number of scripts in your document, and you can have scripts
in both the body and the head section at the same time.

Example

<html>

<head>

<script type="text/javascript">
function message()

alert("This alert box was called with the onload event");

</script>
</head>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

<body onload="message()">
<script type="text/javascript">

document.write("This message is written by JavaScript");


</script>

</body>

</html>

Using an External JavaScript

JavaScript can also be placed in external files. External JavaScript files often contains
code to be used n several different web pages. External JavaScript files have the file
extension .js. External script annot ontain the <script></script> tags. To use an external
script, point to the .js file in the "src" attribute of the <s ript> tag:

Example

<html>

<head>

<script type="text/javascript" src="xxx.js"></script>

</head>

<body>

</body>

</html>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

JavaScript Variables

JavaScript variables are used to hold values or express o s. A variable can have a short
name, like x, or a more descriptive name, like carname. Rul s for JavaScr pt var able
names:
Variable names a case s nsitive (y and Y are two different variables)

Variable names must b gin with a l tt r or the underscore character

Because JavaScript is case-sensitive, va iable names are case-sensitive.

Declaring (Creating) JavaScript Variables

Creating variables in JavaScript is most often referred to as "declaring" variables. You


can declare JavaScript variables ith the var key ord:

var x;

var carname;

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.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Assigning Values to Undeclared JavaScript Variables

If you assign values to variables that have not yet been declared, the variables will
automatically be declared. These statements:

x=5;

carname="Volvo";

have the same effect as:

var x=5;

var carname="Volvo";

Redeclaring JavaScript Variables

If you redeclare a JavaScript variable, it will not lose its original value.

var x=5;

var x;

After the execution of the statements above, the variable x will still h ve the v lue of 5.
The value of x is not reset (or cleared) when you redeclare it.

The Lifetime of JavaScript Variables

If you declare a variable within a funct on, the var able can o ly be accessed within that
function. When you exit the function, the variable is destroyed. These var ables are called
local variables. You can have local variables with the same name in different functions,
because each s recog zed o ly by the function in which it is declared.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
If you declare a variable outside a function, all the functions on your page can access
it. The lifetime of these variables starts when they a d cla d, and nds when the page
is closed.

JavaScript Arithmetic Op ato s

Arithmetic operators a e used to pe fo m arithmetic between variables and/or values.


Given that y=5, the table below explains the arithmetic operators:

Operator Description Example Result

+ Addition x=y+2 x=7

- Subtraction x=y-2 x=3

* Multiplication x=y*2 x=10

/ Division x=y/2 x=2.5

% Modulus (division remainder) x=y%2 x=1

++ Increment x=++y x=6

-- Decrement x=--y x=4

JavaScript Assignment Operators

Assignment operators are used to assign values to JavaScript variables. Given that x=10
and y=5, the table below explains the assignment operators:

Operator Example Same As Result

= x=y x=5

+= x+=y x=x+y x=15


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
-= x-=y x=x-y x=5

*= x*=y x=x*y x=50

/= x/=y x=x/y x=2

%= x%=y x=x%y x=0

Comparison Operators Comparison operators are used in logical statements to


determine equality r difference between variables or values. Given that x=5, the table
below explains the comparison operators:

Operator Description Example

== is equal to x==8 is fa se

=== is exactly equal to (value and type) x===5 is true


x==="5" is fa se

!= is not equal x!=8 is tr e

> is greater than x>8 is fa se

< is less than x<8 is tr e

>= is greater than or equal to x>=8 is f lse

<= is less than or equal to x<=8 is tr e

Logical Operators

Logical operators are used to determine the logic between variables or values. Given
that x=6 and y=3, the table below explains the logical operators:

Operator Description Example

&& and (x < 10 && y > 1) is true

|| or (x==5 || y==5) is false

! not !(x==y) is true

Conditional Operator
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

JavaScript also contains a conditional operator that assigns a value to a variable based on
some condition.

yntax

variablename=(condition)?value1:value2

Example

greeting=(visitor=="PRES")?"Dear President ":"Dear ";

Conditional Statements

Very often when you write code, you want to perform different actions for
different decisions. You can use conditional statements in your code to do this.

In JavaScript we have the following conditional statements:

if statement - use this statement to execute some code only if a specified condition is
true

if...else statement - use this statement to execute some code if the condition is true
and another code if the
condition is false
if...else if....else statement - use this statement to select one of many blocks of code to
be executed
switch statement - use this statement to select one of many blocks of code to be
executed

If Statement
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
Use the if statement to execute some code only if a specified condition is true.

Syntax

if (condition)

code to be executed if condition is true

Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a
JavaScript error!

Example

<script type="text/javascript">

//Write a "Good morning" greeting if

//the time is less than 10

var d=new Date();

var time=d.getHours();

if (time<10)

document.write("<b>Good morning</b>");

</script>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
If...else Statement

Use the if....else statement to execute some code if a condition is true and another code if the
condition is not true.

Syntax

if (condition)

code to be executed if condition is true

else

code to be executed if condition is not true

Example

<script type="text/javascript">

//If the time is less than 10, you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.

var d = new Date();

var time = d.getHours();

if (time < 10)

document.write("Good morning!");
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
}

else

document.write("Good day!");

</script>

If...else if...else Statement

Use the if....else if...else statement to select one of several blocks of code to be exec ted.

Syntax

if (condition1)

code to be executed if condition1 is true

else if (condition2)

code to be executed if condition2 is true

else

code to be executed if condition1 and cond t o 2 are ot true


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
}

Example

script type="text/javasc ipt">


var d = new Date()

var time = d.getHou s()


if (time<10)

document. rite("<b>Good morning</b>");

else if (time>10 && time<16)

document. rite("<b>Good day</b>");

else

document.write("<b>Hello World!</b>");

</script>

The JavaScript Switch Statement

Use the switch statement to select one of many blocks of code to be executed.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Syntax

switch(n)

case 1:

execute code block 1


break;

case 2:

execute code block 2


break;

default:

code to be executed if n is different from case 1 and 2

JavaScript Popup Boxes

JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.

Alert Box

An alert box is often used if you want to make sure information comes through to the user.
When an alert box pops up, the user will have to click "OK" to proceed.

Syntax

alert("sometext");
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
Example

<html>

<head>

<script type="text/javascript">
function show_alert()

alert("I am an alert box!");

</script>

</head>

<body>

<input type="button" onclick="show alert()"


value="Show alert box" /> </body>

</html>

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 ill 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

confirm("sometext");
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
Example

<html>

<head>

<script type="text/javascript">
function show_confirm()

var r=confirm("Press a button");

if (r==true)

alert("You pressed OK!");

else

alert("You pressed Cancel!");

</script>

</head>

<body>

<input type="button" onclick="show confirm()" value="Show


confirm box" /> </body>

</html>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Prompt Box

A prompt box is often used if you want the user to i ut a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Ca cel" to roceed
after entering an input value. If the user clicks "OK" the box returns the input value. If the
user cl cks "Ca cel" the box returns null.

Syntax

prompt("sometext","defaultvalue");

Example

<html>

<head>

<script type="text/javasc ipt">

function show prompt()

var name=prompt("Please enter your


name","Harry Potter"); if (name!=null &&
name!="")

document. rite("Hello " + name + "! How are you today?");

</script>

</head>

<body>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

<input type="button" onclick="show_prompt()" value="Show prompt box" />


</body>

</html>

JavaScript Functions

A function will be executed by an event or by a call to the function.

JavaScript Functions

To keep the browser from executing a script when the page loads, you can put your script
into a functi n. A functi n contains code that will be executed by an event or by a call to the
function. You may call a functi n fr m anywhere within a page (or even from other pages if
the function is embedded in an external .js file). Functi ns can be defined both in the <head>
and in the <body> section of a document. However, to assure that a fun tion is read/l aded
by the browser before it is called, it could be wise to put functions in the <head> section.

How to Define a Function

Syntax

function functionname(var1,var2,...,varX)

some code

}
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

The parameters var1, var2, etc. are variables or values passed into the function. The { and the } defines the
start and end of the function. The word function must be written in lowerc se letters, otherwise a JavaScript
error occurs! Also note that you must call a function with the exact same ca itals s in the function n me

JavaScript Function Example

Example

<html>

<head>

<script type="text/javasc ipt">


function displaymessage()

alert("Hello World!");

</script>

</head>

<body>

<form>

<input type="button" value="Click me!" onclick="displaymessage()"


/> </form>

</body>

</html>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
The return Statement

The return statement is used to specify the value that is returned from the function. So, functions that are
going to return a value must use the return statement. The example below returns the product of two
numbers (a and b):

Example

<html>

<head>

<script type="text/javascript">

function product(a,b)
{

return a*b;

</script>

</head>

<body>

<script type="text/javascript">

document.write(product(4,3));

</script>

</body>

</html>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

JavaScript Loops

Often when you write code, you want the same block of code to run over nd over g in in a
row. Instead of adding several almost equal lines in a script we can use loops to perform t
sk like this.

In JavaScript, there are two different kind of loops:


for - loops through a block of code a specified umber of times

while - loops through a block of code wh le a s ecified condition is true

The for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax

for (variable=startvalue;va iable<= ndvalue;variable=variable+increment)

code to be executed

Example

The example below defines a loop that starts with i=0. The loop will continue to run as long
as i is less than, or equal to 5. i ill increase by 1 each time the loop runs.

Note: The increment parameter could also be negative, and the <= could be any comparing statement.

Example
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
<html>

<body>

<script type="text/javascript">
var i=0;

for (i=0;i<=5;i++)

{
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

document.write("The number is " + i);


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

</script>

</body>

</html>

JavaScript While Loop

Loops execute a block of code a specified number of times, or while a specified


condition is true.

The while Loop

The while loop loops through a block of code while a specified condition is true.

Syntax

while (variable<=endvalue)

code to be executed

Note: The <= could be any comparing operator.

Example
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

The example below defines a loop that starts w th =0. The loop will continue to run
as long as i is less than, or equal to 5. i will increase by 1 each time the loop ru s:

Example

<html>

<body>

<script type="text/javasc ipt">


var i=0;

while (i<=5)

document. rite("The number is " + i);


document. rite("<br />");

i++;

</script>

</body>

</html>

The do...while Loop

The do...while loop is a variant of the while loop. This loop will execute the
block of code ONCE, and then it will repeat the loop as long as the specified
condition is true.

Syntax
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

code to be executed

while (variable<=endvalue);

Example

The example below uses a do...while loop. The do...while loop will always be executed
at least once, even if the condition is false, because the statements are executed before
the condition is tested:

Example

<html>

<body>

<script type="text/javascript">
var i=0;

d
o

document.write("The number is " + i);


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

i++;
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
}

while (i<=5);

</script>

</body>

</html>

The break Statement

The break statement will break the loop and co t ue executi g the code that follows after
the loop (if any).

Example

<html>

<body>

<script type="text/javasc ipt">

var i=0;

for (i=0;i<=10;i++)

if (i==3)

break;

document. rite("The number is " + i);

document. rite("<br />");


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

</script>

</body>

</html>

The continue Statement

The continue statement will break the current loop and continue with the next value.

Example

<html>

<body>

<script type="text/javascript">
var i=0

for (i=0;i<=10;i++)

if (i==3)

continue;

document.write("The number is " + i);

document.write("<br />");
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
}

</script>

</body>

</html>

JavaScript For...In Statement

The for...in statement loops through the elements of an array or through the roperties of
an object.

Syntax

for (variable in object)

code to be executed

Note: The code in the body of the for... n loop s xecuted once for each element/property.

Note: The variable a gum nt can be a nam d variable, an array element, or a property of an
object.

Example

Use the for...in statement to loop through an array:

Example

<html>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
<body>

<script type="text/javascript">
var x;

var mycars = new Array();

mycars[0] = "Saab";

mycars[1] = "Volvo";

mycars[2] = "BMW";

for (x in mycars)

document.write(mycars[x] + "<br />");


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

</script>

</body>

</html>

JavaScript Events

Events are actions that can be detected by JavaScript.

Events

By using JavaScript, we have the ability to create dynamic web pages. Events are actions
that an be dete ted by JavaScript. Every element on a web page has certain events which
can trigger a JavaScript For example, we an use the onClick event of a button element to
indicate that a function will run when a user c i ks on the button. We define the events in
the HTML tags.

Examples of events:

A mouse click
A web page or an image
loading
Mousing over a hot spot on the web
page
Selecting an input field in an HTML
form
Submitting an HTML form
A keystroke
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
Events are normally used in combinat on w th fu ct o s, a d the function will not be
executed before the event occurs.

Event Association

Events are associated with HTML tags. The d finitions of the events described below are as
follows:
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

JavaScript Objects

Object oriented Programming in an important aspect of JavaScript. It is possible to use


built-in objects available in JavaScript. It is also possible for a JavaScript programmer to
define his own objects and variable types. In this JavaScript tutorial, you will learn how to
make use of built-in objects available in JavaScript.

Built-in objects in JavaScript:

Some of the built-in objects available in JavaScript are:

Date

Math
String, Number,
Boolean
RegExp
window (Global Obejct)

JavaScript String Object

Of the above objects, the most widely used one is the String object. Objects re nothing b
t special kind of data. Each object has Properties and Methods associated with it.
property is the v l e th t is tagged to the object. For example let us consider one of the
properties associated with the most o ul rly used String object - the length property.
Length property of the string object returns the length of the string th t is in other words
the number of characters present in the string.

General syntax of using the length property of the stri g object is as below:

variablename.length

Here variablename is the name of the var able to wh ch the stri g is assigned and length is the
keyword.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

For example consider the JavaScript b low:

<html>

<body>

<script type="text/javasc ipt">

var exf="Welcome"

document. rite(exf.length)

</script>

</body>

</html>

The output of the above is

Method of an Object:

Method of an object refers to the actions than can be performed on the object. For example
in String Object there are several methods available in JavaScript.

Example to understand how method can be used in an Object.


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

In the example below, we have used toUpperCase method of String object.

<html>

<body>

<script type="text/javascript">
var exf="Welcome"

document.write(exf.toUpperCase())

</script>

</body>

</html>

The output of the above script is

WELCOME

In the above script since the method toUpperCase is applied to the string object exf
which has value initialized as Welcome all letters get converted as upper case and hence
the output is s bove.

Purpose of String Object in JavaScript:


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
The main purpose of String Object in JavaScript is for stori g text. General method of
using String Object is to declare a variable and assign a string, in other words a text to
the variable.

var exf="Welcome"

assigns the text Welcome to the variable xf d f n d.

String Object Methods

Method

charAt()

charCodeAt()

concat()

indexOf()

lastIndexOf()

match()

replace()
search()

slice()

split()

substr()

substring()

toLowerCase()

toUpperCase()

valueOf()
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

JavaScript Date Object

Usage of Date Object:

Date object of Java Script is used to work with date and times. General syntax for defining
Date bject in Java Script is as follows:

var variablename=new Date( )

In the above new is a keyword which creates an instance of object and Date() defines
variablename as Date Object.

For example:

var exf=new Date( )

In the above example, variable exf is defined as Date object which h s c rrent d te nd time as
its initial value.

Methods of Date Object:

Some of the methods available with Date object are:

setSeconds()- Sets the seconds for a specified date accordi g to local time.

setMinutes() - Sets the minutes for a spec f ed date accord g to local time.

setHours() - Sets the hours for a specif ed date accord g to local time.

setDate() - Sets the day of the month for a specified date accord g to local time.

setMonth() - Sets the month for a specified date accord g to local t me.

setYear() - Sets the year (d pr cat d) for a sp c f d date according to local time.

setFullYear() - Sets the full y ar for a sp cifi d date according to local time.

toString() - Returns a st ing p s nting the sp cified Date object.


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
getSeconds() - Retu ns seconds in the sp cifi d date according to local time.

getMinutes() - Returns minut s in the sp cifi d date according to local time.

getHours() - Returns hour in the sp cifi d date according to local time.

getDay() - Returns day of the week for a specified date according to local time

getDate() - Returns day of the month for a specified date according to local time.

getMonth() - Returns month in the specified date according to local time.

getYear()-Returns year (deprecated) in the specified date according to local time.


getFullYear() - Returns year of the specified date according to local time.

Example for usage of Date Object methods mentioned above:

var exf=new Date()

exf.setFullYear(2020,0,20)

As e have seen setFullYear() is used for Setting the full year for a specified date
according to local time. In the above example the Date object exf is set to the specific
date and year 20th January 2020

Example for using methods of Date Object


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

<html>

<body>

<script type="text/javascript">
var exforsys=new Date();

var currentDay=exforsys.getDate();

var currentMonth=exforsys.getMonth() + 1;
var currentYear=exforsys.getFullYear();

document.write(currentMonth + "/" + currentDay +


"/" + currentYear);

</script>

</body>

</html>

Output of the above program is:

11/15/2006

JavaScript Math Object

Usage of Math Object:

JavaScript Math object is used to perform mathematical tasks. But unlike the String and
the Date object which requires defining the object, Math object need ot be defi ed. Math
object in JavaScript has two main attributes:

Properties
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
Methods

Properties of Math Object:

The JavaScript has eight math matical valu s and this can be accessed by using the
Math Object. The eight mathematical values a e:

PI
square root of 2 denoted as
SQRT2
square root of 1/2 denoted as
SQRT1 2
natural log of 2 denoted as
LN2
natural log of 10 denoted as
LN10
base-2 log of E denoted as
LOG2E

base-10 log of E denoted as LOG10E

The ay of accessing these values in JavaScript is by using the word Math before these values
namely as
Math.E

Math.LOG10E and so on

Methods of Math Object:

There are numerous methods available in JavaScript for Math Object. Some of them are
mentioned below namely:
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

abs(x) - Returns absolute value of x.

acos(x) - Returns arc cosine of x in radians.


asin(x) - Returns arc sine of x in radians.
atan(x) - Returns arc tan of x in radians.
atan2(y, x) - Counterclockwise angle between x axis and point (x,y).

ceil(x) - Returns the smallest integer greater than or equal to x. (round up).
cos(x) - Returns cosine of x, where x is in radians.
exp(x) - Returns ex
floor(x) - Returns the largest integer less than or equal to x. (round down)
log(x) - Returns the natural logarithm (base E) of x.
max(a, b) - Returns the larger of a and b.

min(a, b) - Returns the lesser of a and b.


pow(x, y) - Returns xy
random() - Returns a pseudorandom number between 0 and 1.
round(x) - Rounds x up or down to the nearest integer. It rounds .5 up.
sin(x) - Returns the Sin of x, where x is in radians.
sqrt(x) - Returns the square root of x.

tan(x) - Returns the Tan of x, where x is in radians.

Example for Math Object methods mentioned above:

<html>

<body>

<script type="text/javascript">
document.write(Math.round(5.8))
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
</script>

</body>

</html>

The output of the above p og am is

This is because the round() method rounds the number given in argument namely here 5.8
to the nearest integer. It rounds .5 up hich gives 6.

Another example for using Math Object in JavaScript.

<html>

<body>

<script type="text/javascript">

document.write(Math.max(8,9) + "<br />")

document.write(Math.max(-5,3) + "<br />")

document.write(Math.max(-2,-7) + "<br />")

</script>

</body>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

</html>

The above example uses the max() method of the Math object which returns the largest of
the two numbers given in arguments of the max method.

JavaScript Boolean Object

The Boolean object is used to convert a non-Boolean value to a Boolean value (true or fa se)

Boolean Object Methods

Met Description
hod
Converts a Boolean value to a string, nd
toSt returns the res lt Returns the primitive value
ring of a Boole n object
()

valu
eOf
()

Number Object

The Number object is an object wrapper for pr m t ve umeric values.

Number objects are created with new Number().


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
Syntax

var num = new Numbe (valu );

Number Object Methods

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

toPrecision(x) Formats a number to x length

toString() Converts a Number object to a string

valueOf() Returns the primitive value of a Number object

String Object

The String object is used to manipulate a stored piece of text.

String objects are created with new String().

Syntax

var txt = new String(string);

or more simply:

var txt = string;


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
JavaScript RegExp Object

Regular expressions are used to do sophisticated pattern matching, which can often be
helpful in form validation. For example, a regular expression can be used to check
whether an email address entered into a form field is syntactically correct. JavaScript
supports Perl-compatible regular expressions.

There are two ways to create a regular expression in JavaScript:

1. Using literal syntax

var reExample = /pattern/;


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

2. Using the RegExp() constructor

var reExample = new RegExp("pattern");

Assuming you know the regular expression pattern you are going to use, there is no real
difference between the two; however, if you don't know the pattern ahead of time (e.g,
you're retrieving it from a form), it can be easier to use the RegExp() constructor.

JavaScript's Regular Expression Methods

The regular expression method in JavaScript has two main methods for testing
strings: test() and exe (). The exec() Method

The exec() method takes one argument, a string, and checks whether that string contains one
or more mat hes of the pattern specified by the regular expression. If one or more matches is
found, the method returns a result array with the starting points of the matches. If no match
is found, the method returns n ll.

The test() Method

The test() method also takes one argument, a string, and checks whether th t string
contains a match of the pattern specified by the regular expression. It returns true if it
does cont in m tch nd f lse if it does not. This method is very useful in form validation
scripts. The code sam le below shows how it c n be used for checking a social security
number. Don't worry about the syntax of the regular ex ression itself. We'll cover that
shortly.

Code Sample: RegularExpressions for validati g social


security umber <html>

<head>

<script type="text/javascript">

var exp = /^[0-9]{3}[\- ]?[0-9]{2}[\- ]?[0-9]{4}$/;


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
function f1(ssn)

if (exp.test(ssn)) { ale t("VALID SSN"); }


else { alert("INVALID SSN"); }

</script>

</head>
<body>
<form name=”f1”>

<input type="text" name="t1" />

<input type="button" value="Check"


onclick="f1(this.f1.t1.value);" /> </form>

</body>

</html>

Code Explanation

Let's examine the code more closely:

First, a variable containing a regular expression object for a social security

number is declared. var exp = /^[0-9]{3}[\- ]?[0-9]{2}[\- ]?[0-9]{4}$/;


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Next, a function called f1() is created. This function takes one argument: ssn, which is
a string. The function then tests to see if the string matches the regular expression pattern
by passing it to the regular expression object's test() method. If it does match, the function
alerts "VALID SSN". Otherwise, it alerts "INVALID SSN".

function f1(ssn)

if (exp.test(ssn)) { alert("VALID SSN"); } else


{ alert("INVALID SSN"); }

A form in the body of the page provides a text field for inserting a social security
number and a butt n that passes the user-entered social security number to the f1()
function.

<form >

<input type="text" name="t1" />

<input type="button" value="Check"


onclick="checkSsn(this.form.ssn.va ue);" /> </form>

Flags

Flags appearing after the end slash modify how a regular expression works.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
The i flag makes a regular expression case insensitive. For ex m le, / eiou/i m tches
all lowercase and uppercase vowels.

The g flag specifies a global match, meaning that all matches of the s ecified pattern
should be returned.

Regular Expression Syntax

A regular expression is a pattern that spec f es a l st of characters.

Start and End :^ $

A caret (^) at the beginning of a r gular xpr ssion indicates that the string being
searched must start with this pattern.

* The pattern ^foo can be found in "food", but not in "barfood".

A dollar sign ($) at the end of a egular expression indicates that the string being
searched must end with this pattern.

The pattern foo$ can be found in "curfoo", but

not in "food". Number of Occurrences : ? + * {}

The follo ing symbols affect the number of occurrences of the preceding character: ?, +,
*, and {}.

A questionmark (?) indicates that the preceding character should appear zero or one times in
the pattern.
* The pattern foo? can be found in "food" and "fod", but not "faod".

A plus sign (+) indicates that the preceding character should appear one or more times in the
pattern. *

The pattern fo+ can be found in "fod", "food" and "foood", but not "fd".

A asterisk (*) indicates that the preceding character should appear zero or more times in the
pattern.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

* The pattern fo*d can be found in "fd", "fod" and "food".

Curly brackets with one parameter ( {n} ) indicate that the preceding character should
appear exactly n times in the pattern.

* The pattern fo{3}d can be found in "foood" , but not "food" or "fooood".

Curly brackets with two parameters ( {n1,n2} ) indicate that the preceding character
should appear between n1 and n2 times in the pattern.

* The pattern fo{2,4}d can be found in "food","foood" and "fooood", but not "fod" or
"foooo d".

Curly brackets with one parameter and an empty second paramenter ( {n,} ) indicate that
the pre eding hara ter should appear at least n times in the pattern.

The pattern fo{2,}d can be found in "food" and "foooood",

but not "fod". Common Characters: . \d \D \w \W \s \S

A period ( . ) represents any character except a newline.

The pattern fo.d can be found in "food", "foad",

"fo9d", nd "fo*d". Backslash-d ( \d ) represents any digit.

It is the equivalent of [0-9].

The pattern fo\dd can be found in "fo1d", "fo4d" a d "fo0d", but not in

"food" or "fodd". Backslash-D ( \D ) represents any character except a d g

t. It is the equivalent of [^0-9].

* The pattern fo\Dd can be found in "food" a d "foad", but ot in "fo4d".

Backslash-w ( \w ) repres nts any word charact r (letters, digits, and the underscore ( ) ).
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
* The pattern fo\wd can be found in "food", "fo d" and "fo4d", but not in "fo*d".

Backslash-W ( \W ) ep es nts any cha act r xc pt a word character.

The pattern fo\Wd can be found in "fo*d", "fo@d" and "fo.d",

but not in "food". Backslash-s ( \s) represents any whitespace

character (e.g, space, tab, newline, etc.).

The pattern fo\sd can be found in "fo d", but not in "food". Backslash-

S ( \S ) represents any character except a whitespace character.

The pattern fo\Sd can be found in "fo*d", "food" and "fo4d",

but not in "fo d". Grouping: []

Square brackets ( [] ) are used to group options.

The pattern f[aeiou]d can be found in "fad" and "fed", but not in "food", "faed" or "fd".

The pattern f[aeiou]{2}d can be found in "faed" and "feod", but not in

"fod", "fed" or "fd". Negation : ^


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

When used after the first character of the regular expression, the caret ( ^ ) is used for
negation.

The pattern f[^aeiou]d can be found in "fqd" and "f4d", but not

in "fad" or "fed". Subpatterns: ()

Parentheses () are used to capture subpatterns.

The pattern f(oo)?d can be found in "food" and "fd",

but not in "fod". Alternatives: |

The pipe ( | ) is used to create optional patterns.

The pattern foo$|^bar can be found in "foo" and "bar", but not "foobar".

Escape Character : \

The backslash ( \ ) is used to escape special characters.

* The pattern fo\.d can be found in "fo.d", but not in "food" or "fo4d".

A more practical example has to do matching the delimiter in soci l security numbers.
Examine the following regular expression.

^\d{3}([\- ]?)\d{2}([\- ]?)\d{4}$

Within the caret (^) and dollar sign ($), wh ch are used to specify the beginning and end
of the pattern, there are three sequences of digits, optionally separated by a hyphen or a
space. This pattern will be matched in all of following strings (and more).

123-45-6789

123 45 6789

123456789
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
123-45 6789

123 45-6789

123-456789

The last three strings are not ideal, but they do match the pattern. Back references can be
used to make sure that the second delimiter matches the first delimiter. The regular
expression would look like this.

^\d{3}([\- ]?)\d{2}\1\d{4}$

The \1 refers back to the first subpattern. Only the first three strings listed above match this
regular expression.

Form Validation ith Regular Expressions

Regular expressions make it easy to create powerful form validation functions. Take
a look at the following example.

Code Sample: Login.html

<html>

<head>

<script type="text/javascript">
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

var RE_EMAIL = /^(\w+[\-\.])*\w+@(\w+\.)+[A-Za-z]+$/;


var RE_PASSWORD = /^[A-Za-z\d]{6,8}$/;

function validate()

var email = form.Email.value;

var password = form.Password.value;


var errors = [];

if (!RE_EMAIL.test(email)) { alert( "You must enter a valid email address."); }

if (!RE_PASSWORD.test(password)) { alert( "You must enter a valid password."); }

</script>

</head>
<body>
<form name=”form”>

Email: <input type="text" name="Email" />

Password: <input type="password" name="Password” />

*Password must be between 6 and 10 characters and can only contain letters and digits.

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


onclick=”Validate();”/> <input type="reset"
value="Reset Form" /> </p>

</form>

</body>

</html>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Code Explanation

This code starts by defining regular express o s for an email address and a password. Let's
break each one down.

var RE_EMAIL = /^(\w+\.)*\w+@(\w+\.)+[A-Za-z]+$/;

1. The caret (^) says to sta t at the b ginning. This prevents the user from entering
invalid characters at the beginning of the email add ss

(\w+[\-\.])* allows for a s qu nce of word characters followed by a dot or a dash. The
* indicates that the pattern can be repeated ze o or mo e times. Successful patterns
include "ndunn.", "ndunn-", "nat.s.", and "nat-s-".
\w+ allows for one or mo e wo d characters.

@ allo s for a single @ symbol.

(\ +\.)+ allo s for a sequence of word characters followed by a dot. The + indicates that
the pattern can be repeated one or more times. This is the domain name without the last
portion (e.g, without the "com" or "gov").
6. [A-Za-z]+ allo s for one or more letters. This is the "com" or "gov" portion of the
email address.

The dollar sign ($) says to end here. This prevents the user from entering invalid
characters at the end of the email address.
var RE PASSWORD = /^[A-Za-z\d]{6,8}$/;

The caret (^) says to start at the beginning. This prevents the user from entering
invalid characters at the beginning of the password.

[A-Za-z\d]{6,8} allows for a six- to eight-character sequence of letters and digits.

The dollar sign ($) says to end here. This prevents the user from entering invalid
characters at the end of the pass ord.

Exercises:
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Construct a reg exp to validate a text field which should be used to accept only a string
composed by 3 letters, one space, 6 numbers, a "-" and a number such as MJHJ
123456-6

Ans: /^[A-Za-z]{4}\s\d{6}\-\d{1}$/

2. Write regular expressions to check for:

1. Proper Name

o starts with capital letter

o followed by one or more letters or apostophes o

may be multiple words (e.g, "New York City")

2. Initial

o zero or one capital letters


3. State

o two capital letters


4. Postal Code

o five digits (e.g, "02138")

o possibly followed by a dash and four digits (e.g, "-1234")

5. Username

o between 6 and 15 letters or digits

Add validation to check the following fields:

first name

middle initial

last name

city

state
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
zip

username

Test your solution in a browser.

Document Object

Each HTML document load d into a b ows r window becomes a Document object. The
Document object provides access to all HTML elem nts in a pag , f om within a script.
It describes the JavaScript array object including parameters, properties, and methods.

Parameters

arrayLength

elementN - Array element list of values


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Properties

index

input

length - The quantity of elements in the object.

prototype - For creating more properties.

Methods

chop() - Used to truncate the last character of a all strings that are part of an array. This
meth d is n t defined so it must be written and included in your code.

var exclamations = new Array("Look out!", "Duck!" )

exclamations.chop()

Causes the values of exclamations to become:

Look out

Duck

concat()

grep(searchstring) - Takes an array and returns those arr y element strings th t contain
matching strings. This method is not defined so it must be written and included in your
code.

words = new Array("limit","lines","finish","com lete","I ","Out")


inwords = words.grep("in")

The array, inwords, will be:

lines, finish
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
* join(delimiter) - Puts all l m nts in the array into a string, separating each element with
the specified delimiter.

words = new Ar ay("limit","lin s","finish","complete","In","Out")

var jwords = wo ds join(";")

The value of the st ing jwo ds is:

limit;lines;finish;complete;In;Out

pop() - Pops the last string off the array and returns it. This method is not defined
so it must be written and included in your code.

ords = new Array("limit","lines","finish","complete","In","Out")

var last ord = words.pop()

The value of the string lastword is:

Out

push(strings) - Strings are placed at the end of the array. This method is not defined
so it must be written and included in your code.

words = new Array("limit","lines","finish")


words.push("complete","In","Out")
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

The array, words, will be:

limit, lines, finish, complete, In, Out

* reverse() - Puts array elements in reverse order.

words = new Array("limit","lines","finish","complete","In","Out")


words.reverse()

The array, words, will be:

Out, In, complete, finish, lines, limit

shift() - Decreases array element size by one by shifting the first element off the
array and returning it. This method is not defined so it must be written and included in
your code.

words = new Array("limit","lines","finish","complete","In","Out")

word = words.shift()

The array, words, will be:

In, complete, finish, lines, limit

The string word will be:

Out

* sort() - Sorts the array elements in d ct o ary order or usi g a compare function passed to
the method.

words = new Array("limit","lines","f n sh","complete","I ","Out")

word = words.sort()
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

The value of wo ds b com s:

In,Out,complete,finish,limit,lin s

splice() - It is used to take elements out of an array and replace them with those specified.
In the below example the element starting at element 3 is removed, two of them are removed
and replaced with the specified strings. The value returned are those values that are replaced.
This method is not defined so it must be written and included in your code.

ords = new Array("limit","lines","finish","complete","In","Out")


ords1 =ords.splice(3, 2, "done", "On")

The value of ords becomes:

limit, lines, finish, done, On, Out

The value of words1 is set to:

complete, In

split(deliimiter) - Splits a string using the delimiter and

returns an array. words = new

String("limit;lines;finish;complete;In;Out")
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

var swords = words.split(";")


The values in the array swords is:
limit, lines, finish, complete, In, Out
* unshift() - Places elementa at the start of an array
words = new Array("finish","complete","In","Out")

word = words.shift("limit","lines")
The array, words, will be:
limit, lines,finish, complete, In, Out

Form validation
Form validation is the process of checking that a form has been filled in correctly
before it is processed. For example, if your form has a box for the user to type their
email address, you might w nt yo r form handler to check that they've filled in their
address before you deal with the rest of the form. Form v lid tion is s ally done with
JavaScript embedded in the Web page

Validate text field to accept an age

The above program will accept the input o ly in a y o e of the


following valid form 25 5 101
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
Validate a checkbox
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Validate form selection


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

UNIT –IV

PHP - Working principle of PHP - PHP Variables - Constants - Operators – Flow Control and
Looping - Arrays - Strings - Functions - File Handling - File Uploading – Email Basics - Email with
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
attachments - PHP and HTML - Simple PHP scripts - Databases with PHP

PHP (Hypertext Preprocessor) is a server-side scripting language designed for web development. It
is one of the most popular programming languages for building dynamic websites and web
applications.

The working principle of PHP involves the following steps:

1. Client sends a request: When a user visits a website or interacts with a web application, their
web browser sends a request to the web server.
2. Web server processes the request: The web server (e.g., Apache, Nginx) receives the request
and identifies that the requested file has a .php extension.
3. PHP parser: The web server passes the PHP file to the PHP parser, which is installed on the
server. The PHP parser reads the PHP code line by line and executes it.
4. PHP code execution: PHP is a server-side scripting language, which means that the PHP code is
executed on the server. The PHP interpreter processes the PHP code and generates the
corresponding output.
5. Database and external resources: PHP can interact with databases (e.g., MySQL, PostgreSQL)
and other external resources (e.g., APIs, file systems). It can retrieve data from databases,
modify data, and perform various operations.
6. HTML generation: PHP is often used in combination with HTML (Hypertext Markup
Language). Within the PHP code, HTML can be embedded, allowing dynamic generation of
HTML content based on the logic and data processing performed by the PHP code.
7. Output generation: Once the PHP code is executed, it generates output, typically in the form of
HTML, CSS, JavaScript, or other web content. This output is sent back to the web server.
8. Server response: The web server receives the output generated by PHP and sends it back as a
response to the client's request.
9. Client receives the response: The client's web browser receives the server's response, which
may include HTML, CSS, JavaScript, or other resources. The browser renders the received
content and displays it to the user.

Throughout this process, PHP allows developers to write dynamic and interactive web
applications by incorporating programming logic, database interactions, file operations, and more. It
enables the creation of websites that can respond to user input, handle form submissions, process
data, and generate personalized content.

PHP, variables
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
PHP, variables are used to store and manipulate data. They are containers that hold values and
can be referenced and manipulated throughout the script. Here are some key points about PHP
variables:

1. Variable Declaration: In PHP, you don't need to explicitly declare variables before using them.
You can simply assign a value to a variable, and PHP will automatically create it. For example:

$age = 25 ; $name = "John" ;

In the above code, $age and $name are variables storing an integer and a string value,
respectively.

2. Variable Names: PHP variable names start with the dollar sign ($) followed by a letter or
underscore. They can contain alphanumeric characters and underscores but must begin with a
letter or underscore. Variable names are case-sensitive, so $age and $Age would be treated as
different variables.

3. Variable Types: PHP variables are dynamically typed, meaning that you don't need to specify
their data type explicitly. The data type is determined based on the value assigned to the
variable. PHP supports various data types, including integers, floats, strings, booleans, arrays,
objects, and more.

4. Variable Assignment: You can assign a value to a variable using the assignment operator (=).
The value can be a literal or the result of an expression. For example:

$x = 10 ; $y = $x + 5 ;

In this case, $x is assigned the value 10, and $y is assigned the result of the expression $x + 5,
which is 15.

5. Variable Scope: PHP variables have different scopes, which determine their visibility and
accessibility within different parts of the script. The three main scopes are:

 Global Scope: Variables defined outside of any function or class have a global scope and can be
accessed from anywhere in the script.
 Local Scope: Variables defined inside a function have a local scope and are only accessible
within that function.
 Static Scope: Using the static keyword within a function allows a variable to retain its value
between function calls.

6. Variable Output: To output the value of a variable, you can use the echo or print statements.
For example:

$name = "Alice" ; echo "Hello, " . $name ; // Outputs: Hello, Alice


7. Variable Manipulation: PHP provides various operators and functions for manipulating
variables. You can perform arithmetic operations, concatenate strings, compare values, modify
variable values, and more.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

These are some fundamental aspects of PHP variables. They play a crucial role in storing and
processing data within PHP scripts, enabling dynamic and flexible behavior in web
applications.

PHP constants

In PHP, constants are similar to variables but with one key difference: their values cannot be
changed once they are defined. Constants are useful for storing values that remain constant
throughout the execution of a script. Here are the key points about PHP constants:

1. Constant Declaration: Constants are declared using the define() function or the const keyword.
The general syntax for defining a constant is:
define ( 'CONSTANT_NAME' , value);

or

const CONSTANT_NAME = value;

For example:

define ( 'PI' , 3.14159 ); const WEBSITE_NAME = "MyWebsite" ;

In the above code, PI and WEBSITE_NAME are constants with values 3.14159 and
"MyWebsite" respectively.

2. Naming Conventions: Constants' names are usually written in uppercase letters, although it's
not a strict requirement. Using uppercase letters helps distinguish constants from variables and
makes them more readable.
3. Accessing Constants: Once defined, constants can be accessed throughout the script without the
need for a leading dollar sign ($). To access a constant, simply use its name. For example:
echo PI; // Outputs: 3.14159 echo WEBSITE_NAME; // Outputs: MyWebsite

4. Constant Scope: Constants have a global scope and can be accessed from anywhere in the
script, including inside functions and classes.
5. Predefined Constants: PHP provides several predefined constants that are available for use
without the need for explicit declaration. These include PHP_VERSION, PHP_OS,
PHP_EOL, and more. They provide information about the PHP environment and can be useful
in certain situations.
6. Constant Values: Constant values can be of any scalar type: integers, floats, booleans, or
strings. They cannot be assigned the result of an expression or a function call.
7. Best Practices: It is a common practice to define constants in a centralized location, such as a
configuration file, to make them easily accessible and maintainable throughout the script.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
Constants are beneficial when you have values that should not be modified during the execution
of your PHP script, such as configuration settings, mathematical constants, or fixed strings. By
using constants, you can ensure the integrity of these values and avoid accidental modification.

PHP operators

1. Arithmetic Operators:
 Addition (+): Adds two operands.
 Subtraction (-): Subtracts the second operand from the first.
 Multiplication (*): Multiplies two operands.
 Division (/): Divides the first operand by the second.
 Modulus (%): Returns the remainder of the division operation.
 Increment (++) and Decrement (--): Increase or decrease the value of a variable by one.
2. Assignment Operators:
 Assignment (=): Assigns a value to a variable.
 Addition assignment (+=): Adds the right operand to the left operand and assigns the result to
the left operand.
 Subtraction assignment (-=): Subtracts the right operand from the left operand and assigns the
result to the left operand.
 Multiplication assignment (*=): Multiplies the right operand with the left operand and assigns
the result to the left operand.
 Division assignment (/=): Divides the left operand by the right operand and assigns the result to
the left operand.
 Modulus assignment (%=): Computes the modulus of the left operand with the right operand
and assigns the result to the left operand.

3. Comparison Operators:
 Equal to (==): Checks if the left operand is equal to the right operand.
 Identical to (===): Checks if the left operand is equal to the right operand and of the same type.
 Not equal to (!= or <>): Checks if the left operand is not equal to the right operand.
 Not identical to (!==): Checks if the left operand is not equal to the right operand or not of the
same type.
 Greater than (>): Checks if the left operand is greater than the right operand.
 Less than (<): Checks if the left operand is less than the right operand.
 Greater than or equal to (>=): Checks if the left operand is greater than or equal to the right
operand.
 Less than or equal to (<=): Checks if the left operand is less than or equal to the right operand.

4. Logical Operators:
 AND (&&): Returns true if both the left and right operands are true.
 OR (||): Returns true if either the left or right operand is true.
 NOT (!): Returns the opposite boolean value of the operand.

5. String Operators:
 Concatenation (dot .): Concatenates two strings together.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
 Concatenation assignment (dot equals .=): Appends the right operand to the left operand and
assigns the result to the left operand.

These are just a few examples of PHP operators. PHP also provides bitwise, array, and ternary
operators, among others, for performing specific operations.

Flow Control And Looping Structures

PHP provides several flow control and looping structures to control the execution flow of your
code. These structures allow you to make decisions, repeat code blocks, and iterate over data.
Here are the main flow control and looping structures in PHP:
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
1. If statement: The if statement allows you to execute a block of code conditionally based on a
specific condition. It has the following syntax:

if (condition) { // Code to execute if condition is true } else { // Code to execute if condition


is false }

You can also use elseif to add additional conditions within the same statement.

2. Switch statement: The switch statement allows you to select one of many blocks of code to be
executed. It is useful when you have multiple conditions to check against a single variable.
Here's an example:

switch (variable) { case value1: // Code to execute if variable matches value1 break ; case
value2: // Code to execute if variable matches value2 break ; default : // Code to execute if
variable doesn't match any case break ; }

3. While loop: The while loop executes a block of code as long as a specific condition is true.
The condition is checked before each iteration. Here's an example:

while (condition) { // Code to execute in each iteration }

Do-while loop: The do-while loop is similar to the while loop, but it checks the condition after
each iteration. This guarantees that the code block is executed at least once. Here's an example:

do { // Code to execute in each iteration } while (condition);

4. For loop: The for loop is commonly used when you know the number of iterations in advance.
It has three parts: initialization, condition, and increment. Here's an example:

for (initialization; condition; increment) { // Code to execute in each iteration }

5. Foreach loop: The foreach loop is used to iterate over arrays and objects. It automatically
assigns the current element to a variable for each iteration. Here's an example:

foreach ( $array as $value ) { // Code to execute for each element in the array }

6. Break and continue: Both break and continue are used within loops to control the flow.
break terminates the loop and continues executing the code after the loop, while continue
skips the current iteration and moves to the next iteration.

These flow control and looping structures provide powerful tools to handle different scenarios
in PHP programming, enabling you to control the flow of execution and manipulate data
efficiently.

PHP Arrays , strings , Functions


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
PHP is a versatile programming language that provides several features and functionalities for
working with arrays, strings, and functions. Let's explore each of these topics in more detail.

Arrays in PHP: Arrays in PHP are used to store multiple values in a single variable. They can
hold different data types such as strings, numbers, or even other arrays. PHP provides several
functions and operations to manipulate arrays. Here's an example of creating an array and
accessing its elements:

// Creating an array $fruits = array( "apple" , "banana" , "orange" ); // Accessing array


elements echo $fruits [ 0 ]; // Output: apple echo $fruits [ 1 ]; // Output: banana echo
$fruits [ 2 ]; // Output: orange

Strings in PHP: Strings in PHP are sequences of characters enclosed in quotes. PHP offers
various functions to manipulate strings, including concatenation, splitting, searching, and
replacing. Here's an example demonstrating some string operations:

$name = "John" ; $age = 25 ; // Concatenating strings $greeting = "Hello, " . $name . "!
You are " . $age . " years old." ; echo $greeting ; // Output: Hello, John! You are 25 years old.
// String length echo strlen ( $name ); // Output: 4 // Searching for a substring echo
strpos ( $name , "oh" ); // Output: 1 (position of "oh" in "John") // Replacing part of a string
$newString = str_replace ( "John" , "Jane" , $name ); echo $newString ; // Output: Jane

Functions in PHP: Functions in PHP allow you to encapsulate reusable blocks of code. They
help improve code organization, reusability, and maintainability. Here's an example of defining
and calling a function in PHP:

// Defining a function function greet($name) { echo "Hello, " . $name . "!" ; } // Calling the
function greet ( "John" ); // Output: Hello, John!

You can also pass parameters to functions, return values, use default arguments, and more. PHP
provides a wide range of built-in functions, and you can create your own custom functions to
suit your requirements.

These are just basic examples of working with arrays, strings, and functions in PHP. PHP offers
much more functionality and numerous built-in functions to work with these concepts. Refer to
the official PHP documentation for more detailed information and examples:
https://www.php.net/manual/
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

PHP File Handling - File Uploading

PHP provides various functions and techniques for file handling and file uploading. Here's an
overview of how you can handle file uploads in PHP.

1. HTML Form: Create an HTML form with an input field of type "file" to allow users to select a
file for uploading. Set the form's enctype attribute to "multipart/form-data" to handle file
uploads.
html code

<form action="upload.php" method="POST" enctype="multipart/form-data"> <input


type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload
File" name="submit"> </form>

2. PHP Server-side Handling: In the PHP script that receives the file upload request (in this
example, "upload.php"), you can handle the uploaded file using the $_FILES superglobal
variable.
php code

<?php if( isset ( $_POST [ "submit" ])){ $targetDir = "uploads/" ; // Directory to save the
uploaded files $targetFile = $targetDir . basename ( $_FILES [ "fileToUpload" ][ "name" ]);

$uploadOk = 1 ;

$imageFileType = strtolower ( pathinfo ( $targetFile ,PATHINFO_EXTENSION)); // Check if


the file is an actual file or a fake file

if( isset ( $_FILES [ "fileToUpload" ]))

{ $check = getimagesize ( $_FILES [ "fileToUpload" ][ "tmp_name" ]);

if( $check !== false ) { echo "File is an image - " . $check [ "mime" ] . "." ; $uploadOk = 1 ; }

else { echo "File is not an image." ; $uploadOk = 0; } } // Check if the file already exists

if ( file_exists ( $targetFile ))

{ echo "Sorry, file already exists." ; $uploadOk = 0 ; } // Check file size (optional)

if ( $_FILES [ "fileToUpload" ][ "size" ] > 500000 )

{ echo "Sorry, your file is too large." ; $uploadOk = 0 ; } // Limit allowed file types (optional)
$allowedExtensions = array( "jpg" , "jpeg" , "png" , "gif" );

if (! in_array ( $imageFileType , $allowedExtensions ))


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed." ;

$uploadOk = 0 ;

} // If all checks pass, move the file to the target directory

if ( $uploadOk == 1 )

if ( move_uploaded_file ( $_FILES [ "fileToUpload" ][ "tmp_name" ], $targetFile ))

{ echo "The file " . basename ( $_FILES [ "fileToUpload" ][ "name" ]). " has been uploaded." ;

else

echo "Sorry, there was an error uploading your file." ;

}
} ?>

This script checks various conditions such as file type, size, and existence, and then moves the
uploaded file to the specified directory if all checks pass.

Remember to create the "uploads" directory in the same location as your PHP script to store the
uploaded files.

Note: It's crucial to implement additional security measures such as validating file types,
restricting file sizes, and handling file name collisions to enhance security and prevent
unauthorized access or file execution.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

PHP Email Basics - Email with attachments

Sending emails with attachments in PHP involves a few steps. Here's a basic example to get
you started:

1. Ensure that PHP's built-in mail() function is properly configured on your server. Check your
PHP configuration file (php.ini) or consult your hosting provider to ensure email functionality
is enabled.

2. Create a form or gather the necessary information (sender, recipient, subject, message) and the
file to be attached.

3. Use the $_FILES superglobal array to access the uploaded file. Make sure your form has the
enctype attribute set to "multipart/form-data" for file uploads.

4. Here's an example PHP code snippet to send an email with an attachment:

phpCopy code
<?php // Sender and recipient details
$sender = 'sender@example.com' ;
$recipient = 'recipient@example.com' ;
$subject = 'Email with Attachment' ;
$message = 'Please find the attached file.' ;
// File details
$file = $_FILES [ 'attachment' ];
$attachment_path = $file [ 'tmp_name' ];
$attachment_name = $file [ 'name' ]; // Email headers
$headers = "From: $sender\r\n" ;
$headers .= "Reply-To: $sender\r\n" ;
$headers .= "MIME-Version: 1.0\r\n" ;
$headers .= "Content-Type: multipart/mixed; boundary=" . uniqid ( rand (), true ) . "\r\n" ;
// Email body
$body = "--" . uniqid ( rand (), true ) . "\r\n" ;
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n" ;
$body .= "Content-Transfer-Encoding: 7bit\r\n" ;
$body .= "\r\n" ;
$body .= "$message\r\n" ;
$body .= "--" . uniqid ( rand (), true ) . "\r\n" ;
$body .= "Content-Type: application/octet-stream; name=\"$attachment_name\"\r\n" ;

$body .= "Content-Transfer-Encoding: base64\r\n" ;


$body .= "Content-Disposition: attachment; filename=\"$attachment_name\"\r\n" ;
$body .= "\r\n" ;
$body .= chunk_split ( base64_encode ( file_get_contents ( $attachment_path ))) . "\r\n" ;
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

$body .= "--" . uniqid ( rand (), true ) . "--" ; // Send the email $mail_sent = mail( $recipient ,
$subject , $body, $headers ); if ( $mail_sent ) { echo "Email sent successfully with
attachment." ; } else { echo "Failed to send email." ; } ?>

Make sure to replace sender@example.com and recipient@example.com with the actual


email addresses of the sender and recipient.

Note: The example above uses the mail() function, which is a basic email-sending function in
PHP. For more advanced email handling, you might consider using a library like PHPMailer or
SwiftMailer, which provide more features and flexibility.

PHP and HTML

The combination of PHP and HTML is often used to create dynamic web pages and build web
applications. Here's a basic example of PHP code embedded in HTML:

html code

<!DOCTYPE html>

<html>

<head>

<title> PHP and HTML Example

</title>

</head>

<body>

<h1> Welcome to my website! </h1>

<?php // PHP code $name = "John Doe"; echo "Hello, " . $name . "! This is a dynamic
message."; ?> <p> Thanks for visiting! </p>

</body>

</html>

In the above example, the PHP code (<?php ?>) is used to define a variable $name and echo a
dynamic message containing the variable's value. When the PHP code is executed on the server,
it generates the HTML content that will be sent to the browser. The resulting page will display
the dynamic message "Hello, John Doe! This is a dynamic message."

PHP and HTML can work together to create more complex web applications, including e-
commerce sites, content management systems, and web-based software. They provide the
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
necessary tools for server-side processing, data manipulation, and generating dynamic content
based on user input or database interactions.

Simple PHP scripts

1 .Hello World:

php code

<?php echo "Hello, World!" ; ?>

2. Display Current Date and Time:


phpcode

<?php echo "Current Date and Time: " .

date ( "Y-m-d H:i:s" ); ?>

3. Calculate the Sum of Two Numbers:


php code

<?php

$number1 = 10 ;

$number2 = 20 ;

$sum = $number1 + $number2 ;

echo "Sum: " . $sum; ?>

4. Generate a Random Number between 1 and 10:


php code

<?php $randomNumber = rand ( 1 , 10 );

echo "Random Number: " . $randomNumber ; ?>

5. Check if a Number is Even or Odd:


php code

<?php

$number = 15 ;

if ( $number % 2 == 0 )

{ echo $number . " is even." ; }


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

else { echo $number . " is odd." ;

} ?>

These are just a few examples to get you started. You can build upon them and explore more
complex functionalities based on your requirements.

Databases with PHP

PHP is a popular programming language for web development, and it provides several options
for working with databases. Here are some commonly used databases with PHP:

1. MySQL: MySQL is a widely used open-source relational database management system. It is


often used in combination with PHP due to its ease of use and compatibility. PHP provides
built-in functions and extensions like MySQLi (improved MySQL) and PDO (PHP Data
Objects) for connecting to and interacting with MySQL databases.

2. PostgreSQL: PostgreSQL is another popular open-source relational database management


system. It offers advanced features and supports complex data types. PHP provides extensions
like PDO and PostgreSQL-specific functions for working with PostgreSQL databases.

3. SQLite: SQLite is a lightweight and file-based relational database engine. It is suitable for
smaller applications or when you need a self-contained database file. PHP has built-in

4. support for SQLite, allowing you to work with SQLite databases using PDO or SQLite-speciic
functions.

5. Oracle: Oracle is a powerful and widely used enterprise-grade relational database management
system. PHP provides the OCI8 extension, which enables connectivity to Oracle databases.
OCI8 offers a comprehensive set of functions for interacting with Oracle databases.

6. MongoDB: MongoDB is a popular NoSQL document-oriented database. It stores data in JSON-


like documents and provides flexible and scalable data storage options. To work with
MongoDB in PHP, you can use the MongoDB extension, which offers a convenient API for
connecting to and manipulating MongoDB databases.

These are just a few examples of databases commonly used with PHP. Depending on your
specific needs, there are many other databases and PHP extensions available that you can
explore.

PHP connectivity with MYSQL


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
To connect to a database using PHP, you can utilize the PHP Data Objects (PDO) extension or
the MySQLi extension. Both options provide a convenient and secure way to interact with
databases. Here's an example of how to establish a database connection using PDO:

php code

<?php

$servername = "localhost" ; // Replace with your server name

$username = "your_username" ; // Replace with your database username

$password = "your_password" ; // Replace with your database password

$dbname = "your_database" ; // Replace with your database name

try { $conn = new PDO ( "mysql:host=$servername;dbname=$dbname" ,

$username , $password );

$conn -> setAttribute (PDO:: ATTR_ERRMODE , PDO:: ERRMODE_EXCEPTION );

echo "Connected successfully" ; }

catch (PDOException $e ) {

echo "Connection failed: " . $e -> getMessage (); }

?>

In this example, you need to replace the placeholders ($servername, $username, $password,
and $dbname) with your actual database details.

If the connection is successful, it will output "Connected successfully." Otherwise, it will


display an error message.

Remember to handle your database credentials securely, such as storing them in a separate
configuration file outside of the web root directory and ensuring proper access permissions.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

UNIT -V

Servlets: Java Servlet Architecture – Servlet Life cycle- Form GET and POST actions -
Sessions – Cookies – Database connectivity - JDBC
Creation of simple interactive applications - Simple database applications

Host Objects

JavaScript supports three types of objects: native, host, and user-defined. Native
objects are objects supplied by the JavaScript language. String, Boolean, Math,
and Number are examples of native objects.

Host objects are JavaScript objects that provide special access to the host
environment. They are provided by the browser for the purpose of interaction with
the loaded document. In a browser environment,

window

document

objects are host objects. Several other browser host objects are informal, de facto
standards. They are: alert, prompt, confirm.

DOM

The Document Object Model (DOM) is an API that allows programs to


interact with HTML (or XML) documents

The primary function of the Document Object Model is to view, access, and
change the structure of an HTML document separate from the content cont
ined within it.

The DOM will provide you with methods and properties to retrieve, modify,
pdate, and delete parts of the document you are working on. The properties of
the Document Object Model are used to describe the web page or document
and the methods of the Document Object Model are used for working with
parts of the web page.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
In DOM, HTML document is represented in tree like structure. It constructs
a hierarchical tree structure for a HTML docume t to traverse a d to mani
ulate the document.
For example,

<html>

<head>

<title>Sample Docum nt</t tl >

</head>

<body>

<h1>An HTML Docum nt</h1>


<p>This is a <i>simpl </i> docum nt.

</body>

</html>

The DOM representation of this document is as follows:


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

The node directly above a node is the parent of that node. The nodes one level
directly below another node are the children of that node. Nodes at the same level,
and with the same parent, are siblings. The set of nodes any number of levels below
another node are the dendants of that node.

Types of nodes

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.

Traversing a Document: Counting the number of Tags

The DOM represents an HTML document as a tree of Node objects. With any
tree structure, one of the most common things to do is traverse the tree,
examining each node of the tree in turn. The following program shows one way
to do this.

<html>

<head>

<script>

function countTags(n)

{ // n is a Node

var numtags = 0; // Initialize the tag counter

if (n.nodeType == 1 ) // Check if n is an Element

numtags++; // Increment the counter if so

var children = n.childNodes; // Now get all children of n

for(var i=0; i < children.length; i++)


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
{ // Loop through the children

numtags += countTags(children[i]); // Recurse on each one

return numtags; // Return the total number of tags

</script>

</head>

<body onload="alert('This document has ' +


countTags(document) + ' t gs')"> This is a <i>sample</i>
document.

</body>

</html>

Output

Finding Specific Elements in a Document

The ability to traverse all nodes in a document tree gives us the power to find
specific nodes. When programming with the DOM API, it is quite common to
need a particular node within the document or a list of nodes of a specific type
within the document.

You can use getElementById() and getElementsByTagName( ) methods of


Document Object to obtain a list of any type of HTML element. For example, to
find all the tables within a document, you'd do this:

var tables = document.getElementsByTagName("table");


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

This code finds <table> tags and returns elements in the order in which they appear in the
document.

getElementById( ) to find a specific element whereas getElementsByName( )


returns an array of elements rather than a single element.

The following program illustrates this.

<html>

<head>

<script type="text/javascript">
function f1()

alert(document.getElementById("p1").nodeName);

</script>

</head>

<body>

<p id="p1"> Program is coded to find paragraph element is present in the


doc ment or not using its id attribute</p>

<input type="button" value="Find" onclick="f1();" />

</body>

</html>

Output
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

In the above prog am the method getElementById() finds the specific element
and nodeName is used property return the specific element name.

Modifying a Document: Reversing the nodes of a document

DOM API lies in the features that allow you to use JavaScript to dynamically
modify documents. The follo ing examples demonstrate the basic techniques of
modifying documents and illustrate some of the possibilities.

The follo ing example includes a JavaScript function named reverse( ), a sample
document, and an HTML button that, hen pressed, calls the reverse( ) function,
passing it the node that represents the <body> element of the document. The reverse( )
function loops backward through the children of the supplied node and uses the
removeChild( ) and appendChild( ) methods of the Node object to reverse the order of
those children.

<html>

<head><title>Reverse</title>

<script>

function reverse(n) { // Reverse the order of the children of Node n

var kids = n.childNodes; // Get the list of children

var numkids = kids.length; // Figure out how many children there are

for(var i = numkids-1; i >= 0; i--) { // Loop backward through the children

var c = n.removeChild(kids[i]); // Remove a child

n.appendChild(c); // Put it back at its new position


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
}

</script>

</head>

<body>

<pre>

paragraph #1

paragraph #2

paragraph #3

</pre>

<form>

<input type="button" value="Click Me to reverse"


onclick="reverse(doc ment body);"/> </form>

</body>

</html>

when the user clicks the button, the order of the paragraphs nd of the button re reversed.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Changing element Style

The follo ing program illustrates how to change the element style using DOM properties
and methods.

<html>

<head>

<script type="text/javascript">
function f1()

document.getElementById("p1").style.backgroundColor="red";

</script>

</head>

<body>

<p id="p1"> Program is coded to change the style of the


paragraph</p> <input type="button" value="Change"
onclick="f1();" />
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

</body>

</html>

The method getElementById() gets the paragraph element in the document and the
property style is used to change the background color of the paragraph to “red” as
shown below.

Changing element style

<html>

<head>

<script type="text/javascript">
function f1()

{
var o=document.getElementById(" 1");

o.style.color="red";
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
}

function f2()

{
var o=document.getElementById("p1");

o.style.color="blue";

</script>

</head>

<body>

<p id="p1"> Click

Me

</p>

<form>

<input type=button id="b1" value="RED" onclick=f1() />

<input type=button id="b2" value="BLUE" onclick=f2() />

</form>

</body>

</html>

Output
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Changing HTML Content

This page shows a example of how to change a HTML page's content

<html>

<head>

<script type="text/javascript">
function f1()

document.getElementById("p1").childNodes[0].nodeValue="Fine, thank you.";

function f2()

document.getElementById("p1").childNodes[0].nodeValue="How are you?";

</script>

</head>

<body id="p1">
<pre>

<input type="button" id="b1" value="Question" onclick=f1() />

<input type="button" id="b2" value="Answer" onclick=f2() />

</pre>

</body>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
</html>

After pressing the Question button, it adds the content, How re you?” to the
HTML document and after pressing the Answer button, it replaces the content
“How re you?” with “Fine, thank you”

Removing Element from HTML docum nts

<html>

<head>

<script type="text/javasc ipt">


function f1()

var node=document getElementById("p1");

node.removeChild(node.childNodes[0]);

</script>

</head>

<body >

<pre id="p1"><input type="button" id="b1"


value="Question" /> <input type="button" id="b2"
value="Remove" onclick=f1() /> Example for
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Removing an element from HTML document.


</pre>

</body>

</html>

After pressing the “Remove” button, the element “Question” is removed from the document

Server-side Programming: Servlet

The combination of
HTML
JavaScript

DOM
is sometimes referred to as Dynamic HTML (DHTML). Web pages that
inc ude scripting are often called dynamic pages. Similarly, web server
response can be static or dynamic

Static: HTML document is retrieved from the file system


by the server and the same returned to the client.
Dynamic: In server, a HTML document is gener ted by
program in response to an HTTP request
Java servlets are one technology for producing dynamic server responses.
Servlet is a class instantiated by the server to produce a dynamic response.

Servlet Overview

The following figure illustrates the servlet program worki g rinci le.

When server starts it instantiates servlets


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Server receives HTTP request, determines need for dynamic response

Server selects the appropriate servlet to generate the response,


creates request/response objects, and passes them to a method on the
servlet instance

Servlet adds information to response object via method calls


Server generates HTTP response based on information stored in response
object

Types of Servlet
Generic Servlet

HttpServlet

Servlets vs. Java Applications

Servlets do not have a main() method


Entry point to servlet code is via call to a method doGet() /doPost()
Servlet interaction with end user is indirect via
request/response object APIs Primary servlet
output is typically HTML

Running Servlets

Compile servlet (make sure that JWSDP libraries are on path)

Copy .class file to shared/classes directory

(Re)start the Tomcat web server

If the class is named ServletHello,


browse to
http://localhost:8080/servlet/Servlet
Hello
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

What are Servlets?

Java Servlets are programs that run on a Web or A lication server and act as a
middle layer between a request coming from a Web browser or other HTTP clie t
a d databases or applications on the HTTP server.

Using Servlets, you can collect input from users through web page forms, present
records from a database or another source, and create web pages dy am cally.

Java Servlets often s rve the same purpose as programs implemented using the
Common Gateway Interface (CGI). But Servlets off s v al advantag s in comparison
with the CGI.

Performance is significantly b
tt r.

Servlets execute within the address space of a Web server. It is not necessary to
create a separate
process to handle each client request.
Servlets are platform-independent because they are written in Java.

Java security manager on the server enforces a set of restrictions to protect the
resources on a
server machine. So servlets are trusted.

The full functionality of the Java class libraries is available to a servlet. It


can communicate with applets, databases, or other software via the sockets
and RMI mechanisms that you have seen already.

Servlets Architecture:

Following diagram shows the position of Servelts in a Web Application.


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Servlets Tasks:

Servlets perform the following major tasks:

1. Read the explicit data sent by the clients (browsers). This incl des n HTML form on a
Web page or it could also come from an applet or a custom HTTP client progr m.

Read the implicit HTTP request data sent by the clients (browsers). This includes
cookies, media types and compression schemes the browser underst nds, nd so forth.

3. Process the data and generate the results. This rocess may require talking to a database,
executing an RMI or CORBA call, invoki g a Web service, or com uting the response
directly.

Send the explicit data (i.e., the docume t) to the clients (browsers). This document can be
sent in a variety of formats, includ ng text (HTML or XML), binary (GIF images), Excel,
etc.

Send the implicit HTTP respo se to the cl e ts (browsers). This includes telling the
browsers or other clients what type of docume t s be g retur ed (e.g., HTML), setting
cookies and caching parameters, and other such tasks.

Servlets Packages:

Java Servlets are Java class s un by a w b s rver that has an interpreter that
supports the Java Servlet specification

Servlets can be created using the javax.servlet and javax.servlet.http packages,


which are a standard part of the Java's enterprise edition, an expanded version of the
Java class library that supports large-scale development projects.

These classes implement the Java Servlet and JSP specifications. At the time of
writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.

Java servlets have been created and compiled just like any other Java class. After
you install the servlet packages and add them to your computer's Classpath, you
can compile servlets with the JDK's Java compiler or any other current compiler.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
Servlets - Life Cycle

A servlet life cycle can be defined as the entire process from its creation till the
destruction. The following are the paths followed by a servlet

The servlet is initialized by calling the init () method.

The servlet calls service() method to process a client's request.

The servlet is terminated by calling the destroy() method.

Finally, servlet is garbage collected by the garbage collector of the JVM.

Now let us discuss the life cycle methods in details.

The init() method :

The init method is designed to be called only once. It is called when the servlet is
first created, and n t called again for each user request. So, it is used for one-time
initializations, just as with the init meth d f applets.

The servlet is normally created when a user first invokes a URL corresponding to
the serv et, but you an also specify that the servlet be loaded when the server is first
started.

When a user invokes a servlet, a single instance of each servlet gets created, with
each ser 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 init method definition looks like this:

public void init() throws ServletException {

// Initialization code...
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
}

The service() method :

The service() method is the main method to perform the actual task. The servlet
container (i.e. web server) calls the servic () m thod to handle r quests coming
from the client( browsers) and to write the formatted response back to the cli nt.

Each time the se ver c iv s a qu st for a servlet, the server spawns a new thread
and calls service. The service() method ch cks the HTTP r qu st type (GET,
POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc
methods as appropriate.

Here is the signature of this method:


public void service(ServletRequest request,

ServletResponse response)

thro s ServletException, IOException{

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 client.

The doGet() and doPost() are most frequently used methods with in each service
request. Here are the signature of these two methods.

The doGet() Method

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.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

// Servlet code

The doPost() Method

A POST request results from an HTML form that specifically lists POST as the
METHOD and it should be handled by doPost() method.

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Servlet code

The destroy() method :


The destroy() method is ce at the e d of the life cycle of a servlet. This method
called only o gives your
servlet a chance to close ect o s, halt background threads, write cookie lists or
database co hit counts to
disk, and perform other such cleanup act v t es.

After the destroy() method is called, the servlet object is marked for garbage
collection. The destroy
method definition looks like
this:

public void dest oy() {


// Finalization code

}
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Architecture Diagram:
The
follo ing figure depicts a typical servlet life-cycle nario.
First the HTTP requests coming to the server are delegated to the servlet
container.
The servlet container loads the servlet before invoking the service()
method.
Then the servlet container handles multiple requests by spawning multiple
threads, each thread executing the service() method of a single instance of the
servlet.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Structure of a servlet program

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class NewServl t xt nds HttpS rvl t

public void doGet(HttpS vl tR qu st r qu st, HttpServletResponse response)

throws Se vletExc ption, IOExc ption

{
("text/html"); PrintWriter out = response.getWriter(); try
r {
e
s
p
o
n
s
e

s
e
t
C
o
n
t
e
n
t
T
y
p
e
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
type of the response
//
cont
ent // used to create a response as a Html doc

out.println("<html>");

---------------------

---------------------

out.println("</html>");

}catch(Exception e){}

}}}
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

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

Sample Code for Hello World:

Following is the sample source code structure of a servlet example to write Hello World:

Import required java libraries


import java.io.*;

import javax.servlet.*;
import
javax.servlet.http.*;

Extend HttpServlet class

public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException

Do required initialization
message = "Hello
World";
}

public void doGet(HttpServletRequest request, HttpServletResponse response)


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
throws ServletException, IOException

Set response content type


response.setContentType("text/ht
ml");

Actual logic goes here.

PrintWriter out = response.getWr ter(); out.pr tl ("<html><body><b>"

+ message + “</b></body></html>"); out.close();

public void dest oy() { }

Output:

finally type http://localhost:8080/HelloWorld in browser's


address box. If everything goes fine, you ould get following
result:

Parameter data and Query Strings


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
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. Here it is “name=Raj&color=Red”,
in which name and color are parameter names and “Raj” and “Red” are parameter values.
Printthis is a servlet filename and servelt is a directory. Multiple parameters are separated
by &. All parameter values are strings by default. Parameter names and values can be any
8-bit characters.
The following methods are used to process these parameter data in sevlets.

The following program explains how to process these p r meter n mes nd v lues as
well as path of the resource using servlet.

Example program

import java.io.*;

import java.util.*;
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
import javax.servlet.*;

import javax.servlet.http.*;

public class NewServl t xt nds HttpS rvl t

public void doGet(HttpS vl tR qu st r qu st, HttpServletResponse response)


throws Se vletExc ption, IOExc ption
{
response setContentTyp ("t xt/html”);

PrintWriter out = esponse.getWriter();

try {

out.println("<html>");

out.println("<head>"); out.println("<title>Servlet

Ne Servlet</title>"); out.println("</head>");

out.println("<body>");

out.println("Servlet file NewServlet is at: " +


request.getContextPath()); Enumeration
para1=request.getParameterNames();

hile(para1.hasMoreElements())

{
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
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){}
}
}
}

The method getContextPath() of HttpServeltRequest object is used to get the location


of the res urce

The method getParameter() is used to get the value of the parameter.


The method getParameterNames() is used to return the paranameter
names as well. It returns enumeration. The following code in the ab
ve program is used to retrieve the parameter names from the
enumeration.

Enumeration para1=request.getParameterNames();

while(para1.hasMoreElements())

out.println("Parameter name:"+para1.nextElement());

}
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
Output:

Forms and Parameter data:(Passing values from HTML document to Servlet)

A form automatically generates a query str g when submitted. The


parameter name specified by value of name attributes of form
controls. For example,

where username is the pa am t name.

Parameter value can be the value of value attribute of any form control
or it may be the value received from the user by the cont ol at un time.
For example,

The follo ing program explains how to send the data to server
from a web page and the same how to receive it from the server.

html>
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
<head>

</head>

<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, Htt ServletRes onse response)


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
throws ServletException, IOExcept on {

response.setContentType("text/html");

PrintWriter out = response.getWr ter();

try {

out.println("<html>");

out.println("<h ad>"); out.println("<title>Servlet

NewServlet</titl >"); out.p intln("</h ad>");

out println("<body>");

String s1 = equest getPa ameter("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);

out.println("Age:" + s3);

out.println("E-mail:" + s4);

out.println("</body>");

out.println("</html>");

} catch(Exception e) {}
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Output

GET vs. POST method for forms:

GET:

It is used to process the query string which is part of URL

If the length of query string is limited it may be used.


It is recommended when parameter data is not stored but sed on y to req est
information.
POST:

It is used to process the query string as well as to store the d ta on server.


If the Query string is sent as body of HTTP request, the post method will be sed
to retrieve.
If the length of query string is unlimited, it can be used
It is recommended if parameter data is intended to c use the server to update
stored data
Most browsers will warn you if they are about to resubmit POST d ta to avoid
duplicate updates

Important note:

For the HTTP S ss on, Cookies, URL rewriting use our

class not s. The soft copy for these topics will be given
later.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Database connectivity - JDBC

DBC (Java Database Connectivity) is a Java API that provides a standard way for Java
programs to interact with relational databases. It allows Java applications to perform
various database operations such as connecting to a database, executing SQL queries, and
retrieving or updating data.

Here are the basic steps involved in establishing database connectivity using JDBC:

1. Import the JDBC library: First, you need to import the JDBC library into your Java program.
You can do this by including the appropriate JDBC driver JAR file in your project or by
using a build tool like Maven or Gradle to manage dependencies.

2. Load the JDBC driver: Before you can connect to a database, you need to load the
appropriate JDBC driver using the Class.forName() method. The driver class name varies
depending on the specific database you are using. For example, if you're using MySQL, you
would load the driver using Class.forName("com.mysql.jdbc.Driver").

3. Establish a database connection: To connect to a database, you need to provide the


necessary connection information such as the database URL, username, and password. You
can use the DriverManager.getConnection() method to establish a connection. The URL
format also depends on the database you're working with. For example, for MySQL, the
URL might look like jdbc:mysql://localhost:3306/mydatabase.

4. Create a statement: Once you have a database connection, you can create a Statement or a
PreparedStatement object to execute SQL queries. Statements allow you to execute static
SQL queries, while PreparedStatements are used for queries with parameters.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

5. Execute SQL queries: Use the executeQuery() method of the Statement or


PreparedStatement object to execute SELECT queries that retrieve data from the database.
For other types of queries like INSERT, UPDATE, or DELETE, you can use executeUpdate().

6. Process the results: If your query returns results, you can iterate over the ResultSet object
to retrieve the data. You can use methods like next(), getString(), getInt(), etc., to
access the values returned by the query.

7. Close the resources: After you have finished using the ResultSet, Statement, and
Connection objects, it's important to close them to release database and system resources.
You can use the close() method on these objects to do so.

These are the basic steps involved in establishing database connectivity using JDBC. It's
important to handle exceptions appropriately, use connection pooling for performance
optimization, and follow best practices for secure database access.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

UNITWISE – 2 MARKS & 16 MARKS

UNIT – I

1. What is the difference between node and host?

A node is any addressable device connected to a network whereas the host is a more specific
descriptor that refers to a networked general-purpose computer rather than a single purpose device
(such as a printer).

2. What is the purpose of routers?

Router operates like electronic postal workers that evaluate and forward packets between
networks.

3. Define protocol.

A protocol is a formal set of rules that must be followed in order to communicate.

4. Why are the protocols layered?


Layering protocols simplifies the task of communic ting over the network and

it allows for reuse of layers that are not s ecific to rticul r pplic tion.

5. Define encapsulation.

Placing the data inside a package of headers is known as encapsulation.


6. Define port.

A port is a logical chan el to an application running on a host. ie., The applications running on
the host mach es are u iquely identified by port numbers.

7. What do you mean by w ll-known ports?


Port numb s can ange from 1 to 65535, however ports 1 to 1023 are
reserved. These es v d po ts are r f rred to as we1l-known ports because the Internet
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
Assigned Numbe s Autho ity publicly documents the applications that use them.

8. What is meant by Name Resolution?

Name Resolution is the process of mapping a hostname to its corresponding IP Address.One


ay to translate a hostname to an IP address is to look it up in a simple text file. The second ay is the
domain name service, which is a distributed database containing all registered hostnames on the
Internet and their IP addresses.

9. Define protocol tunneling.

Protocol tunneling is the process of encapsulating one protocol within another protocol that
operates on the same layer.

10. Define URI, URL, URN.


1. URI (Uniform Resource Identifier): It identifies an object on the Internet.
URL (Uniform Resource Locator): It is a specification for

URN (Uniform Resource Name): It is a method for referencing an object without


declaring the full path to the object.

11. What are the components of HTTP URL?

The components are host, an optional port, path, filename, section and query string.
12. Define URL encoding.

URL encoding involves replacing all unsafe and nonprintab e hara ters with a percent sign
(%) followed by two hexadecimal digits corresponding to the character’s ASCII value.

13. What are the issues of next generation IP?


The issues to be considered in IP next gener tion
are I. Addresses Space Growth
1. Support large Global networks
2. A clear way of transition from the existing IP to new IP next generation

12. What is the difference between TCP a d UDP?

TCP:
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
Connection oriented tra sport protocol
Sends data as a stream of bytes
Guarantee of delivery
UDP:
Connection l ss p otocol

Datag am s vice

No gua ant of d liv ry.

13. What does ICMP provide?


ICMP provides
1. Error messaging

1. Demand reply functions

14. Define IGMP.


It is Internet Group Management protocol. It provides
1. Broadcasting

2. Multicasting

15. List the goals of SGML.

I. To manage the flow of millions of pages.

2. For structuring information exchange

3. For modeling inter-document linkages

4. For managing information flows between departments and weapons systems

16. What is the role of server?


Manages application tasks

Handles storage

Handles security
Provides scalability
Handles accounting and distribution
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
17. What are the necessities of using HTML forms?
Gathering user information
Conducting Surveys
Interactive services

18. What are the sequences of steps for each HTTP request from a c ient to the server?
Making the connection
Making a request
The response
Closing the connection

19. Define MIME.


MIME (Multipurpose Internet Mail Extensions) is n open st ndard
for sending multipart, multimedia data through Internet em il.
20. List the predefined MIME co te t ty es.
Text
Multipart
Message
Image
Audio
Video
Model
Application

21. Define HTML

It is a simple page description language, which enables document creation for the .

22. What is the role of server?


Manages application tasks

Handles storage

Handles security
Provides scalability
Handles accounting and distribution

23. What are the necessities of using HTML forms?


Gathering user information
Conducting Surveys
Interactive services
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
24.What are the sequences of steps for each HTTP request from a c ient to the server?
Making the connection
Making a request
The response
Closing the connection

25. Define CGI -Common Gateway Interface.


A specification for transferring information between a World Wide Web server and a CGI
program. ACGI program is any program designed to accept and return data that
conforms to the CGI specification. The program could be written in. any programming
language, including C, Perl, Java, or Visual Basic.

UNIT II

26. Write a note on Internet Information Server (IIS).

Microsoft’s Web server that runs on Windows NT platforms, In fact, IIS


comes bundled with Windows NT 4.0. Because IIS is tightly integrated with the
operating system, it is relatively easy to administer. However, currently IIS is available
only for the Windows NT

platform, whereas Netscape’ s Web servers run on all major platforms, including
Windows NT platform, OS/2 and UNIX.

27. What are ISAPI (Internet Server API) and NSAPI (Netscape Server API)

ISAPI (Internet Server API): An API for Microsoft’s IIS (Internet Inf
rmati n Server) Web server. ISAPI enables programmers to develop Web-based appli
ati ns that run much faster than conventional CGI programs because they’re more
tightly integrated with the Web server. In addition to IIS, several Web servers from
companies other than Microsoft support ISAPI.

NSAPI -Netscape Server API: An API for Netscape’s Web servers. NSAPI
enables programmers to create Web-based applications that are more sophisticated and
run much faster than applications based on CGI scripts.

28. What is API -Application Program Interface?

A set of routines, protocols, and tools for building softw re applications. A


good API makes it easier to develop a program by providing ll the building blocks. A
programmer puts the blocks together.

Most operating environments, such s MS- Windows, provide an API so


that programmers can write applications consistent with the o erating environment.
Although APIs are designed for programmers, they are ultimately good for users
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
because they guarantee that all programs us ng a common API will have similar
interfaces. This makes it easier for users to learn new programs.

29. What are Servlets?


A small program that runs on a server, the term usually refers to a Java applet
that runs within environment. This is analogous to a Java applet that runs
within a Web browser.Java se vl ts a b coming increasingly popular as an alternative to CGI
programs.

The biggest diffe ence b tw n the two is that a Java applet is persistent. This means that once it

is started, it stays in memo y and can fulfill multiple requests. In contrast, a CGI
program disappears once it has fulfilled a request. The persistence of Java applets
makes them faster because there’s no asted time in setting up and tearing down the
process.

30. What are Applets?

A program designed to be executed from within another application.


Unlike an application, applets cannot be executed directly from the operating system.
With the

gro ing popularity of OLE (object linking and embedding), applets are becoming
more prevalent. A well-designed applet can be invoked from many different
applications.

Web browsers, who are often equipped with Java virtual machines, can
interpret applets from Web servers. Because applets are small in files size, cross-
platform compatible, and highly secure (can’t be used to access users©hard drives),
they are ideal for small Internet applications accessible from a browser.
31. What do you mean by Server-side?
Occurring on the server side of a client-server system. For example, on
the World Wide Web, CGI scripts are server-side applications because they run on
the Web server. In contrast, JavaScript scripts are client-side because they are
executed by your browser (the client). Java applets can be either server-side or
client- side depending on which computer (the server or the client) executes them.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

32. What is a protocol?

An agreed-upon format for transmitting data between two devices.


The protocol determines the following:

1.The type of error checking to be used

2.Data Compression method, if any

3.How the sending device will indicate that it has finished sending a message

4.How the receiving device will indicate that it has received a message

33. What is ActiveX?

A loosely defined set of technologies developed by Microsoft for sharing


information among different applications. ActiveX is an o tgrowth of two other Microsoft
technologies called OLE (Object Linking and Embedding) nd COM (Component Object
Model). As a moniker, ActiveX can be very confusing bec se it pplies to a whole set of COM-
based technologies. Most people, however, think only of ActiveX controls, which represent a
specific way of implementing ActiveX technologies.

34. Write a note on ActiveX controls.

A control using ActiveX tech ologies. An ActiveX control can be


automatically downloaded and executed by a Web browser. ActiveX is not a
rogramming language, but rather a set of rules for how appl cat o s should share i
formation. Programmers can develop ActiveX controls in a variety of la guages, cludi
g C, C++, Visual Basic, and Java.

An ActiveX control is similar to a Java applet. Unlike Java applets, however, ActiveX
controls have full acc ss to the W ndows operating system. This gives them much more
power than Java appl ts, but with this power comes a certain risk that the applet may
damage software or data on your machine. To control this risk, Microsoft developed a
registration system so that b ows s can id ntify and authenticate an ActiveX control before
downloading it Another diffe ence between Java applets and ActiveX controls is that Java
applets can be w itten to un on all platforms, whereas ActiveX controls are currently limited
to Windo s environments Related to ActiveX is the scripting language VBScript that enables
Web authors to embed interactive elements in HTML documents.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
35.Explain about HTTP Connection.

It is a communication channel between web browser and web server. It begins on the
client side with the browser sending a request to the web server for a document.
Request Header Fields are
From
Reference
If modified since
Pragma
User Agent

36. What is meant by Stateless Connection?


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
When a web server receives a HTTP request from a web browser it evaluates the
request and returns the requested document, if it exists, and then breaks the HTTP connection.
This document is preceded by the response header, which has details about how to display the
document that will be sent by the server. Each time a request is made to the server, it is as if
there was no prior connection and each request can yield only a single document. This is known
as Stateless Connection.

37. Write a note on Environment variables.

In CGI, the server prepares the environment variables before it laun hes the CGI
script. These represent the current state of the server that is asking for the informati n. The
environment variables are not set from the command line but are created on the fly, and lasts
only until that particular script is finished. Each script gets its own unique set of variables and
multiple scripts can be executed at once, each in its own environment

38. What are STDIN and STDOUT?

These are mnemonics for standard input and standard o tp t, two predefined stream /
file handles. Each process already inherits these two h ndles already open. From the script’s
point of view, STDIN is what comes from the browser via the server when the post method is
used, and the STDOUT is where it writes its output b ck to the browser. The script

picks up the environment variables and reads STDIN s ropri te. It then does whatever it was
designed to do and writes its output to STDOUT.

39. What are the two commonly used Request methods?

The request methods tell the scr t how it was invoked. Based on this information, the
script decides how to act. The request method is passed to the script using environment variable
called REQUEST- METHOD. The two most common request methods used are GET and
POST.

GET

GET is a qu st for data, the same method used for obtaining static
documents. The GET method sends qu st info mation as parameter tacked onto the
end of the URL. These parameters are pass d to the CGI program in the environment
variable QUERY-STRING.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
E g : If the sc ipt is called myprog.exe and is invoked from a link with the
form <A HREF="cgi-bin/myp og.exe? lname=blow&fname=joe"> The
REQUEST_METHOD

ill be the string GET, and the QUERY STRING will contain lname=blow &
fname=joe. A mandatory question mark separates the name of the script from the
beginning of the QUERY STRING. If a slash is used instead of the question mark; the
server passes

the information to script using the PATH_INFO variable instead of


the QUERY STRING variable.

POST
POST operation occurs when the browser sends data from a fill -in form to the
server. With POST, the QUERY_STRING mayor may not be blank, depending on the
server.The data from a POSTed query gets passed from the server to the script using
STDIN. Because STDIN is a stream and the script needs to know how much valid data
is waiting, the server also Supplies another variable, CONTENT_LENGTH, to indicate
the size in bytes of the incoming "data.

The format for POSTed data is

Variable1=value1 & variable2=value2 &etc


After the required data is available, the script executes and writes its output to the STDOUT. The
MIME code that the server sends to the browser indicates the type of the file that is being sent. This
information that precedes the file is usually called the header. Since the script generates the output
on the fly the server will not be able to create a header for that

information. Hence this information has to be supplied by the script itself. Failure will
result in the browser receiving information that it does not know how to display.

40. Explain about URL Encoding.

HTTP specification requires that the URL data should be encoded in such a way
that it can be used on almost any hardware and software platforms. Information spe ified
in this way is called URL encoded. If parameters are passed as a part of query string r
path information, they will take the form of ‘Name-Value’ pairs.
variablel=valuel&variable2=value2& so on for each variable defined in the form

The variables or name value pairs are separated by ©&©.Real ampersand is es aped -that
is, encoded as a two-digit hexadecimal value representing the character Escaped
characters are indicated in URL-encoded string by the percent (%) sign. Blank spaces are
rep aced by ©+©sign. Before the script can deal with the data it has to parse and decode
it. The script scans through the string looking for an ampersand. When it is fo nd the
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
string is broken from that point. The variable©s name is every thing up to the eq l sign in
the string and the value is every thing after the equal sign. The script continues to p rse
the original string for the next ampersand, and so on until the original string is exh usted.
After the variables are separated, they are decoded as follows.

Replace all plus signs with blank spaces.


Replace all %## (Percent sign followed by two hexadecimal digits) with the
corresponding ASCII character.
Separate the name-value pairs from the URL a d store the values separately.
41. List the advantages of CGI scr pt ng?
I. CGI programs are r lat v ly safe to run.

A CGI p og am can crash without damaging the server, since it only has
limited access to the s v .
Reduces the bu d n of s rv r
a Sends p epa ed messages / mails e customer reply

b Capability to p ocess forms and prepares output based on form


input. c Hit counts / Page counters.

42.Explain about Session tracking.


A session is basically a conversation between a browser and a server. All the above
technologies can save information for the current session for a particular user visiting a site. The
session is important, as H1TP is a stateless protocol. This means that the connection bet een eb
server and a web browser is not automatically maintained, and that the state of a eb session is
not saved.

State is a general term that includes "everything about your situation" and the specifics
vary based on the application. In a word processor, the state of the application would include
which windows are open, where they are on the screen, and what files you most recently used. In
a web application, the state would include any data that you had entered, the results of any
queries that you had run, and your security access information (e.g. whether you have logged in
to the site).
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

UNIT III

43. Define packet switched networks.

Packet switched network means that data traveling on the network is


broken into chunks called packets and each packet is handled separately.

44. Define socket.

The socket is a software abstraction used to represent the terminals


of a connection between two machines or processes.

45. What are the basic operations of client sockets?


Connect to a remote machine
Send data Receive
data Close a connection

46.What are the basic operations of Server


socket?
Bind to a port
Listen for incoming data
Accept connections from remote machines on the bound port

47.List all the socket classes in java.


Socket
ServerSocket
Datagram Socket
Multicast Socket
Secure sockets

48.What the Socket Object does?

Socket object is the ava r pr s ntat on of a TCP connection when a socket is


created; a connection is op n d to the sp cifi d destination.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
49. What is meant by S v Sock t?

ServerSocket p s nts a list ning TCP connection. Once an incoming


connection is requested, the Se ve Socket object will return a Socket object
representing the connection.

50. What do you mean by DatagramSocket and DatagramPacket?

DatagramSocket represents a connectionless datagram socket. This class works


with the DatagramPacket class to provide for communication using the UDP protocol.

51. Write a note on Connect Exception.

This exception is raised when a connection is refused at the remote host.


(ie, no process is listening on that port).

52. What is a multicast socket?

Multicasting sends data from one host to many different hosts, which
are in the multicast group.

53. What is multicast address and the range of address?

A multicast address is the address of a group of hosts called a multicast group.

Multicast addresses are IP addresses in the range 224.0.0.0 to 239.255.255.255

54. What are the different types of IP addresses?

Unicast address: It is used for transmitting a message to single destination node

Multicast address: It delivers a message to a group of destination nodes, which are


necessarily in the same sub network.

Broadcast address: It transmits a message to all nodes in a sub network.

55. What is meant by protocol handler?


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

Protocol handlers are used to retrieve the web objects using appli
ation specific protocols. The protocols are specified in the URL referencing
the obje t

56. How are the protocol handlers implemented?


Four different classes in the java.net package implement the protocol hand ers:
URL
URLStreamHandler
URLConnection
URLStreamHandlerFactory

What are the methods for parsing URLs?


parseURL(URL u, String spec, int start, int limit)- splits the URL into parts

setURL(URL u, Sring protocol, Stri g host, int port, String file, String ref) -
assigns values to the URL’s f elds.

What is content handler?

Content handlers are used to retr eve objects via an URLConnection object.

59. What is Remote M thod Invocation?

The Remote M thod Invocation is application-programming interface that


allows java objects on diff nt hosts communicate with each other.

60. What do you mean by emote object?

Objects that have methods that can be called across virtual machines are remote

objects.

61. Define serialization.

It is the process of converting a set of object instances that contain


references to each other into a linear stream of bytes, which can then be through a
socket. It is the mechanism used by RMI to pass objects between Java Virtual
Machines.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

62. What are the responsibilities of stub?

A stub for a remote object is the client side proxy for the remote object. A client side
stub is responsible for:

1.Initiating a call to the remote object

2.Marshaling arguments to a marshal stream


3.Informing the remote reference layer that the call should be invoked

4.Unmarshaling the return value or exception from a marshal stream


63. What is the role of skeleton in RMI?

A skeleton for a remote object is a server side entity that contains a method which
dispatches calls to the actual remote object implementation. The skeleton is responsible
for 1.Unmarshaling arguments from the marshal stream.
2.Making the up-call to the actual remote object.

3.Marshalling the return value of the call to an exception onto the Marshall stream

64. List down the layers of RMI architecture


. 1.Stubs/Skeletons
2.Remote reference layer
3.Transport layer

65.Define Object Activation.

Object Activation is mechanism, which llows j va object to be bound and


then activated at some later data simply by referencing the object thro gh the Registry.

66. Write down the Socket object methods to get inform tion bout socket.
getInetAddress ()- displays which remote host the Socket is connected to
getPort () -displays which port the Socket is connected to on the remote host.
3. getLoca1Port ()- to fi d the ort umber for the local end of a connection

4. getLocalAddress () -tells you which Network interface a socket is bound to.


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

67. What operations Multicast Socket Perform?


Join a multicast group
Send data to the m mb rs of the group
Receive data f om the group
Leave the multicast group

UNIT IV

68. What are Style Sheets?

Style sheets are collections of style information that are applied to plain text.
Style information includes font attributes such as type size, special effects
(bold,italic,underline), color and alignment. Style sheets also provide broader formatting
instructions by specifying values for quantities such as line spacing and left and right
margins.

69. List do n the ways of including style information in a document.

1.Linked Styles -Style information is read from a separate file that is specified in
the <LINK> tag

2.Embedded Styles -Style information is defined in the document head using


the <STYLE> and </STYLE> tags.

3.Inline Styles -Style information is placed inside an HTML tag and applies to all
content between that tag and it companion closing tag.

70. Define cascading.

Cascading refers to a certain set of rules that browsers use, in cascading


order, to determine how to use the style information. Such a set of rules is useful in
the event of conflicting style information because the rules would give the browser a
way to determine which style is given precedence.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

71. What are the style precedence rules when using multiple approaches?

Inline styles override both linked style sheets and style information st red in
the document head with <STYLE> tag.

Styles defined in the document head override linked style sheets.


Linked style sheets override browser defaults.

Give the syntax to specify a characteristic in linked style sheet


{Characteristic: value}

Multiple characteristic/value pairs should be separated by semico ons

List down font characteristics permitted in style sheets.

1.font-family

2.font-size

3.font-weight

4.font-style

5.font-variant

74. Write a note on content positio i g characteristic "Visibility".

Enables the document author to selectively dis lay or conceal positioned


content; Possible values are show or h de.

75. Define XML.

XML is a m ta-markup language that provides a format for describing


structured data. This facilitat s more structur d d clarations of content and more
meaningful search results across multiple platfo ms.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
76. Define DTD

A DTD is a set of ules that specifies how to use XML markup. It contains
specifications for each element, including what the element’s attributes are, what
values the attributes can take on and what elements can be contained in others.

What are the XML rules for distinguishing between the content of a document and
the XML markup element?
1.The start of XML markup elements is identified by either the less than symbol
(<) or the ampersand (&) character

2.Three other characters, the greater than symbol (>), the apostrophe or single
quote (‘) and the double quotation marks (“) are used by XML for markup.

3.To use these special characters as content within your document, you must use
the corresponding general XML entity.

78. Define scriptlets.

Scriptlets enable you to create small, reusable web applications that can be
used in any web page. Scriptlets are created using HTML, scripting and Dynamic
HTML. To include them in an HTML document use the <OBJECT> tag.

79. Define ASP.

Active Server Pages (ASP) is a server-side scripting technology that can be


used to create dynamic and interactive web applications.

80. What are the ASP objects?

1.Application -It manages your web application.


2.Session -It manages and tracks individual user
sessions. 3.Server -It controls behavior of your web
server

4.Response -It transmits information from the web server to web browser

5.Request -It retrieves information from the browser for processing at the server.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
81. What is global.asa file?

The global.asa file is a Active Server Application file you can track and manage
the application and session events, variables and objects. When you start the app ication
the server will load the global.asa file into memory.

82. Define response object and list its methods.

The response object transmits information from the web


server to browser. Methods are:
1.Write
2.BinaryWrite
3.Redirect
4.AppendToLog
5.AddHeader
6.Clear

7.Flush

83. Define JSP.

Java Se v Pag s (JSP) are simple technology used to generate dynamic


HTML on the server side

84. Define Di ectives

Directives are JSP elements that provide global information about an entire JSP page.

85. Write do n the various attributes for the page directives in JSP.

The page directive defines information that will be globally available for
that Java Server Page,
language
extends
import
session
buffer
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
contenttype

86. What is meant by firewall?

A firewall is a piece of network hardware that serves as a secure gateway betweenan


internal network and the Internet. It protects the internal network from unauthorized
access or activity,

87. Write a note on proxy server.

A proxy server is a host that makes Internet request on behalf of other machines
on the network, Proxy servers are often used to cache frequently requested files or to
onitor Internet use within a Corporation.

88. What does DHTML refer?

DHTML refers to collection of technologies, which makes HTML do


uments more dynamic and interactive.

89.Define SSI.

Server Side Includes (SSI) gives you a way to insert the content of another file
into a file before the web server processes it.

90.What does data binding mean?

Data binding is DHTML feature that lets you e sily bind individ al elements
in your document to data from another source such s d t b se or comma delimited text
file.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

UNIT- 5
ON LINE APPLICATION
91. What is meant by Plug-in?

A hardware or software module that adds a s ecific feature or service to a


larger system. The idea is that the new compo e t s m ly lugs in to the existing system.
For example, there are number of plug- s for the Netscape Navigator browser that
enable it to display different types of aud o or v deo messages. Navigator plug-ins are
based on MIME file types.

92. What do you mean by JDBC?

JDBC Pa t of the Java D v lopment Kit which defines an application-


programming inte face for Java for standard SQL access to databases from Java
programs.

93. Define ODBC

It is a standard for accessing different databse systems. There are interfaces


for Visual Basic, Visual C++, SQL and the ODBC driver pack contains drivers for the
Access, Paradox, dBase, Text, Excel and Btrieve databases.
94. List any two keyboard events?
onKeypress
2 .onKeyUp
onKeyDown
95.List any two mouse events?
l. onMouseUp
onMouseDown
onMouseOver
onClick
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

94.Define virtual organization.

The virtual organization is defined as being closely coupled


upstream with its suppliers and downstream with its customers such that
where one begins and the other ends means little to those who manage the
business processes within the entire organization.

95.List the major approaches to form virtual organization?


I. Downward networking: a large, vertically integrated company seeking
to reduce its overhead by outsourcing initiates it

2. Lateral Approach: It is observed in small, specialized firms that in


the interest of seeking strategic alliances, form partnerships along a value-added
chain.

96.What do mean by search engine?

It is a program or web page that enables you to search an


Internet site for a specific keywords or words.

97. List the features of online shopping.


1.Make it easy for you to browse and purch se s m ch s possible
from
their websites.

2.Products displayed from the online store re ssoci ted with links to
detailed descriptions of the products
3.You are able to compare the roduct to simil r roducts b sed on the features
and
pricing.
4.It also brings you to the web sites of the roduct manufacturer for
more information.

5.Shopping sites want you to have a perso al account created before


you shop their site. The account typically prov des the busi ess with your
name, address, e-mail, phone number and possibly cred t card numbers.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
6.Some online shopp ng s t s offer free samples. For example,
online music stores sometime have audio samplings of the CDs they sell

98.. How do sea ch ngine wo k?

When you enter a keyword, the search engine examines its


online database and presents to you a listing of sites that, in theory ,
match your search criteria.

PART B

 Explain in detail the working of the TCP/IP and HTTP protocols


 Explain in detail about web client and web-server communication
 Briefly explain any five XHTML controls
 Explain about HTML elements in detail

 How do you use frame collections to access objects in a separate frame on your
ebpage

 Explain how functions can be written in Java script with an example


 Explain any eight CSS text properties in detail
 Explain the way in which java script handles arrays with example
 State and explain the types of statements in java script?
 Explain about the document tree in detail

 Describe the servlet architecture and the various information invoked by the servlet
container.

 Explain DOM event handling in detail

 What is a session? Explain how client state is maintained using session and also
explain about session tracking and session management using an example
 List the XML syntax rules in detail and Explain how a XML do ument an be
displayed on a browser

 Consider the database table with the following structure Student (studentname,

 register_number, Grade obtained, Age) Write a JSP to display a the detai s of


the Student
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

ASSESSMENT QUESTION PAPER -1

Reg. No.

Question Paper Code A

ST. PETER’S COLLEGE OF ENGINEERING AND TECHNOLOGY


AVADI, CHENNAI 600 054

INFORMATION TECHNOLOGY

FOURTH SEMESTER

IT3401 – WEB ESSENTIALS

(Regulations 2021)

Duration: 3 Hours Max. Marks 100

Answer ALL Questions

PART-A (10  2 = 20 Marks)

K-Level CO

1 Why HTTP is called as stateless protocol. 4 1

2 State the functions of a Web Server. 2 1

3 How is session tracking achieved by URL rewriting? 1 2

4 Justify the need for client side scripting. 4 2

5 Write XHTML program to display data in a table. 2 2

6 List and explain any two HTML elements. 1 1

7 Write the CSS which adds background images and indentation. 4 2

8 Write a JavaScript code to change a background color using buttons. 3 3

9 Differentiate between Null value and undefined value in JavaScript 2 3


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
10 How will you create a password field in a HTML form? 6 2

PART – B ( 5  13 = 65 marks)

Note: Single Question for 13 marks or Maximum of 3 split up questions with


Marks K-Level CO
total sum of 13 marks.

11. a) Create a HTML document that displays a table of basketball scores at


national games in which the team names have their respective team colors. 13 6 1
The score of the leading/winning team should appear larger and in a
different font than the losing team. Use CSS.

OR

b) Create a Web page and divide the web page into four equal
13 4 2
parts each individual part displays different web page

12. a) i) Name some new features which were not present in HTML but are added to
HTML5? (7)
13 6 1
ii) Write an HTML code to form a table to show the below values in a tabular
form with heading as Roll No., Student name, Subject Name, and values as.(6)

OR

b) (i) Explain the capabilities of web client and web server. (7)
13 4 1
(ii) Write and explain HTTP request message format. (6)

13 a) (i) Write a Java Script to display a welcome message using alert whenever a
button of a html form is pressed.
13 5 2
(ii) Write CSS code that defines five classes of paragraph with different
background.

OR

b) Discuss the text properties of CSS with suitable example. 13 2 2

14. a) (i) Write a Java Script program that asks for user name, password, mail id,
phone number field in HTML file and validate them by taking assumptions(7) 13 5 2
(ii) Demonstrate about the types of cascading style sheets.(6)
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE
OR

b) Create a HTML document for a hospital home page. 13 6 2

15. a) (i)Explain the use of relative URL’s with an example. (7)

(ii)Explain how tables can be inserted into a HTML document with an example. 13 4 2
(6)

OR

b) Explain HTML forms in detail along with form elements, attributes and
methods. Write an HTML document to provide a form that collect name and 13 4 2
telephone numbers.

PART C (1  15 = 15)

Note: Application/Design/Analysis/Evaluation/Creativity/Case Study


Marks K-Level CO
questions.

16. a) (i) List and explain in detail various selector strings. (8) 15 6 2
(ii) Explain the features of cascading style sheets. (7)
OR

b) List and describe the CSS Border Style Properties in detail with
15 4 2
illustration.

Distribution of COs (Percentage wise)

Evaluation CO1 CO2 CO3 CO4 CO5

Marks 62 118 - - -

% 34.4 65.4 - - -

Note: Including the Choice, the Total Marks will be 180. Each CO must cover around 30 marks or

16.67%.

Prepared By Approved By

[D.SUJATHA,AP/IT] HOD /IT


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

ASSESSMENT QUESTION PAPER -II

Question Paper Code A

ST. PETER’S COLLEGE OF ENGINEERING AND TECHNOLOGY


AVADI, CHENNAI 600 054

INFORMATION TECHNOLOGY

FOURTH SEMESTER

IT3401 – WEB ESSENTIALS

(Regulations 2021)

Duration: 3 Hours Max. Marks 100

Answer ALL Questions

PART-A (10  2 = 20 Marks)

K-Level CO

1 Give the suitable example for basic syntax of PHP 4 4

2 Analyze the difference between “Insert”, “Update” and “Modify” events? 4 4

3 List any three advantages of java servlet over JSP. 4 4

4 Compare GET and POST request type. 4 4

5 How to write and execute PHP document 6 4

6 Analyze about java scriplet 4 5

7 Rewrite the code segment to store current server time in session using Java Servlet API. 6 5

8 Write a simple Servlet program to print the contents of HTML. 5 5

9 Formulate the three methods that are central to the life cycle of the servlet. 6 5

10 How to get the server information in a servlet? 4 5


ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

PART – B ( 5  13 = 65 marks)

Marks K-Level CO

11. a) Explain the various String operations in PHP with an example 13 4 4

OR

i) Write PHP Program to print whether given number is odd or even. (6).

b) 13 4 4

(ii) Discuss the various modes of operation in file handling. (7)

Construct a PHP script to compute the Square root, Square, Cube and
12. a) 13 6 4
Quad of 10 numbers.

OR

Explain the various control and looping statements in PHP with


b) 13 4 4
examples

Design a simple HTML form and accept the user name and display the
13 a) 13 6 4
name through PHP echo statement.

OR

Create a form containing information Sl.No,title of the book , publishers,


b) 13 6 4
quantity, price ,read the data from the form and display it using PHP Script.

Evaluate a Java Servlet to display net salary of employee, use JDBC


14. a) 13 5 5
connectivity to get employee details from database.

OR

Consider a database that has a table Employee with two columns Employee Id
and Name. Assume that the administrator user id and password to access to
b) access the database table are Scott and Tiger. Write a JDBC program that can 13 5 5
query andprint all entries in the table employee. Make the database using type
2 driver databases.
ST. PETER'S COLLEGE OF ENGINEERING & TECHNOLOGY: CHENNAI
Affiliated to Anna University, Chennai & Approved by AICTE

15. a) Write a servlet to illustrate the principle of Cookies and explain. 13 5 5

OR

Explain the ways of storing and accessing information using cookies and
b) 13 5 5
handling associated issues.

PART C (1  15 = 15)

Note: Application/Design/Analysis/Evaluation/Creativity/Case K-
Marks CO
Study questions. Level

16. a) (i)Integrate how servlets work and its lifecycle.(7)


15 6 5
(ii)Explain and develop the Servlet API.(8)

OR

b) Design a Servlet program to display the waiting list status, given


the PNR number of a train. Create a JSP to display the information 15 6 5
at the client end.

Distribution of COs (Percentage wise)

Evaluation CO1 CO2 CO3 CO4 CO5

Marks - - - 88 92

% - - - 48.8 51.2

Note: Including the Choice, the Total Marks will be 180. Each CO must cover around 30 marks or

16.67%.

Prepared By Approved By

[D.SUJATHA, AP/IT] HOD /IT

You might also like