[go: up one dir, main page]

0% found this document useful (0 votes)
81 views61 pages

Web Technologies

The document discusses HTML tags and their usage. It explains the basic structure of an HTML document and different types of HTML tags such as paired tags and singular tags. It also describes the difference between logical and physical HTML tags.

Uploaded by

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

Web Technologies

The document discusses HTML tags and their usage. It explains the basic structure of an HTML document and different types of HTML tags such as paired tags and singular tags. It also describes the difference between logical and physical HTML tags.

Uploaded by

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

[PROF.M.N.

DESHMUKH] Mentor Classes

CHAP 1: HTML.................................................................................................................................................................... 2
CHAP2: CSS....................................................................................................................................................................... 18
CHAP3:JAVAScript............................................................................................................................................................ 23
CHAP 4:VBScript............................................................................................................................................................... 33
CHAP 5: XML..................................................................................................................................................................... 46
CHAP 6:ASP- Microsoft Active Server Pages................................................................................................................. 55

1
[PROF.M.N.DESHMUKH] Mentor Classes

CHAP 1: HTML
Hypertext Markup Language: HTML has a very well defined syntax; all HTML documents should follow a formal
structure. The World Wide Consortium (W3C) is the primary organization that attempts to standardize HTML.
The W3C has defined HTML as an application of Standard Generalized Markup Language (SGML). SGML is a language
used to define other languages by specifying the allowed document structure in the form of a document type definition
(DTD), which indicates the syntax that can be used for the various elements of a language such as HTML.
The language used to develop web pages is called HyperText Markup Language. It is a language interpreted by a Browser.
Web pages are also called as HTML documents.
HTML is a set of special codes that can be embedded in text to add formatting & linking information. HTML is
specified as TAGS in an HTML document.
An HTML document is simply a text file that contains information you want to publish. It also contains embedded
instructions, called elements, which indicates how a web browser should structure or present the document.
Hypertext: Enables you to read & navigate text & visual information in a non-linear way, based on what the user wants to
know.
World Wide Web: WWW can be describe as a global, interactive, dynamic, cross platform, distributed, graphical
hypertext information system that runs over Internet.
Web Page: A page that can contain text, table, images, links, sound & video files etc. & designed by using HTML.
Web Browser:
" Is used to view & navigate web pages & other information on WWW.
" Deals with formatting & displaying web documents.
" Browser takes information it gets from web server in the form of HTML format, & displays it for your system.
" Browser is on client side.
Web Server:A web server is a program that runs on a web site & is responsible for replying to web browser requests for
files.A web server is needed to publish documents on web, & also responsible for managing form input & for linking
forms & browsers with programs such as a database running on server.
When browser gives a request for particular page on a web site, it makes a connection with web server using
HTTP protocol.Server accepts connection, sends the contents of files, that were requested & then closes the connection.
Browser then formats information it got from server.
Uniform Resource Locator:
URL is a pointer to a specific bit of information on the Internet.
URL contain information about:
Name of protocol to use: like FTP, HTTP etc.
Internet host name showing where to look
The directory or other location on that site to find a file.
Using HTTP Protocol

Sends Request

Web Web
Sends Response Server
Client
2
[PROF.M.N.DESHMUKH] Mentor Classes

HTML Tags:Tags are instructions that are embedded directly into the text of the document. An HTML tag is a signal to
browser that it should do something other than just throw text up on the screen.By convention all HTML tags begin with
an open angle bracket (<) & end with a close angle bracket (>).

HTML tags can be of two types:


1.Paired Tags: A tag is said to be a paired tag if, along with a companion tag, contains the text. In paired tag, the first tag
is often called as opening tag, which activates the effect & second tag is called the closing tag which turns the effect off.
2.Singular Tags or Stand-alone tag: Does not have a companion tag.
Rules Of HTML:
HTML is not case sensitive.
HTML is sensitive to a single white space character. Browsers will collapse white space between characters down
to a single element. This includes all tabs, line breaks & carriage returns.
HTML supports a Content Model: HTML supports a strict content model i.e. certain elements are supported to
only occur within other elements.
Browsers ignore unknown attributes & elements.
Logical & Physical HTML
1. Physical HTML: refers to using HTML to make pages look particular way.
2. Logical HTML: refers to using HTML to specify these structures of a document while using another technology,
such as Cascading Style Sheet.
Logical Inline Tags vs. Physical Inline tags
Logical Tags: Logical tags are designed to describe (to the browser) the enclosed text's meaning. An example of a logical
tag is the <strong> </strong> tag. By placing text in between these tags you are telling the browser that the text has some
greater importance.
By default all browsers make the text appear bold when in between the <strong> and </strong> tags, but the point
to take away from this is that the strong tag implies that importance of that text. This has impact with search engines like
Google who look for such tags to help figure out what the page is about.There are many logical tags and they include:
<strong> : Strong - as above.
<em> : emphasize - usually renders (made to look like by the browsers) as italic.
<span> : a neutral inline container. - read about this distinction below.
<div> : a neutral block element. - read about this distinction below.
Logical tags, as mentioned above, have default ways in which browsers (like IE or Opera) render them. But it is
understood that CSS should be used to give them their style, or in other words their 'look'.

Physical Tags: Physical tags on the other hand provide specific instructions on how to display the text they enclose.
Examples of physical tags include:
<b> : Makes the text bold.
<big> : Makes the text usually one size bigger than what's around it.
<font> : Used to apply a font-face (like Arial or Helvetica) and font-color.
<i> : Makes text italic.
Physical tags are more straightforward; <i> makes the text italic, <b> makes text bold and <font> is used to set the font
face and color for the text.
When to Use Logical Markup
Try to use the logical constructs whenever they fit the meaning you're trying to convey.
3
[PROF.M.N.DESHMUKH] Mentor Classes

When you want a header at the top of a page, the <H1> tag is a good choice. The alternative of using a physical <FONT
SIZE="+3"> tag has the negative effect of not logically connoting a header; any program that attempts to create a
structural outline of your document from its headers will be frustrated when you don't mark them as such.
When To Use Physical Markup
When you want to achieve particular visual effects that don't fit into the structural meanings of the various logical tags,
then the physical tags are a better way to do it than the abuse of logical tags for meanings not intended.
Thus, if you decide to boldface all body text just because it looks better to you that way, use the <B> tag instead of the
<STRONG> tag since "strong emphasis" isn't the semantic connotation here.
Example:
<html>
<head>
<title> Title of page </title>
</head>
<body>
This is my first homepage. <b> This text is bold </b>
</body>
</html>
Tag Attributes:Tags can have attributes. Attributes can provide additional information about the HTML elements on your
page.
Example:This tag defines the body element of your HTML page: <body>. With an added bgcolor attribute, you can tell
the browser that the background color of your page should be red, like this: <body bgcolor="red">.
This tag defines an HTML table: <table>. With an added border attribute, you can tell the browser that the table should
have no borders: <table border="0">
HTML commands:The entire web page is enclosed within <HTML></HTML> tags. Within tags two distinct sections are
created using the <HEAD></HEAD> tags & the <BODY></BODY> tags.
Document Head:Information placed in this section is essential to the inner workings of the document.
<HEAD>
<TITLE> </TITLE>
</HEAD>
A web page could have a title that describes what the page is about. Text included between the tag shows up in a title bar
of browser window.
Document Body: The tags used to indicate the start & end of the main body of textual information are: <BODY>
</BODY>Page defaults like background color, text color, font size, font weight etc. can be specified as attributes of
<BODY> tag,Attributes Of Body Tag:
1. BGCOLOR: Changes the default background color. The user can specify a color by name or its equivalent
hexadecimal number.
2. BACKGROUND: Specifies the name of Gif file that will be used as the background of the document.
3. TEXT: Changes the body text color.
Ex:
<BODY BACKGROUND=”computer.gif” TEXT=red>
The .gif file should be present in the current working directory, if not relative path should be specified to where the .gif
file exists.
Ex:
<BODY BACKGROUND=”images/computer.gif” TEXT=red>
Comments in HTML:
4
[PROF.M.N.DESHMUKH] Mentor Classes

The comment tag is used to insert a comment in the HTML source code. A comment will be ignored by the browser. You
can use comments to explain your code, which can help you when you edit the source code at a later date.
<!-- This is a comment -->

Basic HTML Tags


Tag Description
<html> Defines an HTML document
<body> Defines the document's body
<h1> to <h6> Defines header 1 to header 6
<p> Defines a paragraph
<br> Inserts a single line break
<hr> Defines a horizontal rule
<!--> Defines a comment
HTML defines a lot of elements for formatting output, like bold or italic text.
Below are a lot of examples that you can try out yourself:

Text Formatting Tags:


Tag Description
< b> Defines bold text
<big> Defines big text
<em> Defines emphasized text
<i> Defines italic text
<small> Defines small text
<strong> Defines strong text
<sub> Defines subscripted text
<sup> Defines superscripted text
<u> Defines italic text

HTML Links:
HTML uses the <a> (anchor) tag to create a link to another document. An anchor can point to any resource on the Web: an
HTML page, an image, a sound file, a movie, etc.
1. href attribute:The syntax of creating an anchor:
<a href="url">Text to be displayed</a>
The <a> tag is used to create an anchor to link from, the href attribute is used to address the document to link to, and the
words between the open and close of the anchor tag will be displayed as a hyperlink. This anchor defines a link to yahoo
site: The line below will look like this in a browser: Visit Yahoo!
<a href="http://www.yahoo.com/">Visit Yahoo!</a>

2. The Target Attribute:With the target attribute, you can define where the linked document will be opened. The line
below will open the document in a new browser window:

5
[PROF.M.N.DESHMUKH] Mentor Classes

<a href=http://www.yahoo.com/ target="_blank">Visit Yahoo!</a>

Definition and Usage:The <a> tag defines an anchor. An anchor can be used in two ways:
1. To create a link to another document by using the href attribute
2. To create a bookmark inside a document, by using the name or id attribute
Source Output
<p>Linking to WebSchools: Linking to W3Schools: WebSchools
<a href="http://www.webschools.com"> Opening W3Schools a new browser window:
WebSchools</a> WebSchools
</p>
<p> Opening WebSchools a new browser window:
<a href="http://www.webschools.com"
target="_blank">WebSchools</a> </p>

HTML Frames:
With frames, its possible to display more than one Web page in the same browser window.
Frames:Each HTML document is called a frame, and each frame is independent of the others.
The disadvantages of using frames are:
- The web developer must keep track of more HTML documents
- It is difficult to print the entire page
Frame Tags
Tag Description
<frameset> Defines a set of frames
<frame> Defines a sub window (a frame)
<noframes> Defines a noframe section for browsers that do not handle frames
<iframe> Defines an inline sub window (frame)

The Frameset Tag:The <frameset> tag defines how to divide the window into frames. Each frameset defines a set of
rows or columns. The values of the rows/columns indicate the amount of screen area each row/column will occupy
The frameset element defines a frameset. It is used to organize multiple windows (frames). Each frame holds a separate
document. In its simplest use, the frameset element states only how many columns or rows there will be in the frameset.
Attribute Value Description
cols Pixels,%,* Defines the number and size of columns in a frameset
rows Pixels,%,* Defines the number and size of rows in a frameset

The Frame Tag:The <frame> tag defines what HTML document to put into each frame. Defines a sub window (a
frame). You cannot use the <body></body> tags together with the <frameset></frameset> tags!
In the example below we have a frameset with two columns. The first column is set to 25% of the width of the browser
window. The second column is set to 75% of the width of the browser window. The HTML document "frame_a.htm" is
put into the first column, and the HTML document "frame_b.htm" is put into the second column:

6
[PROF.M.N.DESHMUKH] Mentor Classes

<frameset cols="25%,75%">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
</frameset>

Example 1:
<a href="planets.htm" target="_blank">View this page for the result</a>
The source code in "planets.htm":
<html>
<frameset cols = "25%, 25%,*">
<frame src ="venus.htm" />
<frame src ="sun.htm" />
<frame src ="mercur.htm" />
</frameset>
</html>

HTML Images:
In HTML, images are defined with the <img> tag. The <img> tag is empty, which means that it contains
attributes only and it has no closing tag.
To display an image on a page, you need to use the src attribute. Src stands for "source". The value of the src
attribute is the URL of the image you want to display on your page. The syntax of defining an image:
<img src="url">
The URL points to the location where the image is stored. An image named "boat.gif" located in the directory "images" on
"www.webschools.com" has the URL: http://www.webschools.com/images/boat.gif.
The Alt Attribute :
The alt attribute is used to define an "alternate text" for an image. The value of the alt attribute is an author-defined text:
<img src="boat.gif" alt="Big Boat">
The "alt" attribute tells the reader what he or she is missing on a page if the browser can't load images. The browser will
then display the alternate text instead of the image. It is a good practice to include the "alt" attribute for each image on a
page, to improve the display and usefulness of your document for people who have text-only browsers.
Image Tags
Tag Description
<img> Defines an image
<map> Defines an image map
<area> Defines a clickable area inside an image map
<img> tag:The img element defines an image.
Attribute Value Description
Alt Text Defines a short description of the image
Src URL The URL of the image to display
Align Top,bottom,middle Specifies how to align the image according to surrounding text.
left,right Deprecated. Use styles instead
7
[PROF.M.N.DESHMUKH] Mentor Classes

Border Pixels Defines a border around an image. Deprecated. Use styles instead
Height pixels,% Defines the height of an image
Width Pixels,% Sets the width of an image
Hspace Pixels Defines white space on the left and right side of the image. Deprecated.
Use styles instead
Vspace Pixels Defines white space on the top and bottom of the image. Deprecated. Use
styles instead
Ismap URL Defines the image as a server-side image map
Usemap URL Defines the image as a client-side image map. Look at the <map> and
<area> tags to figure out how it works
Ex: Insert images
<html> <body>
<p>An image:<img src="constr4.gif" width="144" height="50"></p>
<p>A moving image:<img src="hackanm.gif" width="48" height="48"></p>
</body> </html>

<map> tag:Defines a client-side image-map. An image-map is an image with clickable regions.


Tips and Notes
Note: The area element is always nested inside the map element. The area element defines the regions in the image map.
Note: The usemap attribute in <img> refers to the id or name (browser dependant) attribute in <map>, therefore we
have added both the id and name attributes to <map>.
<p>Click on one of the planets:</p>
<img src ="planets.gif" width ="145" height ="126" alt="Planets" usemap ="#planetmap" />
<map id ="planetmap" name="planetmap">
<area shape ="rect" coords ="0,0,82,126" href ="sun.htm" target ="_blank" alt="Sun" />
<area shape ="circle" coords ="90,58,3" href ="mercur.htm" target ="_blank" alt="Mercury" />
<area shape ="circle" coords ="124,58,8" href ="venus.htm" target ="_blank" alt="Venus" />
</map>

What is an ImageMap?
In ImageMaps different parts of the page activate different links. ImageMaps are special images containing
different areas that point to different link locations. The place on the image where the mouse clicked determines the place
on the site to which it points.
There are 2 types of ImageMaps:
A. Server-Side ImageMaps:
Server side imagemaps are implemented using an image displayed by the client and a program that runs
on server.When a browser activates a link on a server-side imagemap, it calls a special imagemap program stored on a
web server. The browser also sends x, y coordinates of the position, on the image, where mouse was clicked.
The imagemap program then looks up a special map file that matches regions in the image to URLs,
performs some calculations to determine which page to load & then loads the page.
The problems with server-side imagemaps are: You cannot use or test server-side imagemaps with local files. It requires
the use of a web server to run the program & process coordinates.

8
[PROF.M.N.DESHMUKH] Mentor Classes

As request goes to server every time, imagemaps are slower to respond to mouse clicks than normal links or image links.
Creating a server-side image map:
1) First map all click able regions in image.
2) Then set URLs to link to for each region or point that is selected.
3) Save all these things in a .map file on a server, it may look like this:
Default URL
circle URL x, y , radius
rect URL x, y, x, y
poly URL x1, y1, x2, y2…. XN, vN
point URL x, y
4) In addition to image map file, its necessary to install a server-side image map program on server. These usually
are placed into a special directory called cgi-bin, which is setup to server programs and scripts. Linking it together:
Example: <a href=”/cgi-bin/imagemap/maps/myimage.map”>
<img src=”image.gif” ismap>

B. Client-Side ImageMaps:
Works same as server-side imagemaps, except no program runs on the server. All the processing of coordinates
and pointers to different locations occurs in the browser.
Client-side imagemaps remove all difficulties of server-side imagemaps; they manage all image map processing locally on
the web browser.
Creating Client-side image maps:
To include client-side imagemap inside HTML doc., use <map> tag.
<map name=”mapname”> Coordinates & links </map>
Between <map> tags, enter the co-ordinates & destinations with <area> tag.
Ex:<area shape=”circle” coords=”175,152,50” href=”music/home.html” alt=”home page for music section”>
After defining imagemap, put image on web page. Use a special attribute of <img> tag i.e. usemap.
Ex: <img src=”image.gif” usemap=”#mapname”>

HTML Tables:
Tables are defined with the <table> tag. A table is divided into rows (with the <tr> tag), and each row is divided
into data cells (with the <td> tag). The letters td stands for "table data," which is the content of a data cell.
A data cell can contain text, images, lists, paragraphs, forms, horizontal rules, tables, etc.
How it looks in a browser:
<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>

9
row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2
[PROF.M.N.DESHMUKH] Mentor Classes

<tr> tag : Defines a row in a table.


Attribute Value Description
Align Right,left,center Defines the text alignment in cells
justify,char
Bgcolor rgb(x,x,x) Specifies the background color of the table cell. Deprecated. Use styles
#xxxxxx instead.
colorname
Valign Top,middle,bottom Specifies the vertical text alignment in cells
baseline
<td> tag: Defines a cell in a table.
Attribute Value Description
Align Left,right,center Specifies the horizontal alignment of cell content
justify,char
Bgcolor rgb(x,x,x), #xxxxxx Specifies the background color of the table cell. Deprecated. Use styles
colorname instead.
Colspan Number Indicates the number of columns this cell should span
Height Pixels Specifies the height of the table cell. Deprecated. Use styles instead.
Nowrap Nowrap Whether to disable or enable automatic text wrapping in this cell.
Deprecated. Use styles instead.
Rowspan Number Indicates the number of rows this cell should span
Valign Top,middle,bottom,baseline Specifies the vertical alignment of cell content
Width Pixels,% Specifies the width of the table cell. Deprecated. Use styles instead.

<caption> tag:This element defines a table caption. The <caption> tag must be inserted immediately after the <table>
tag. You can specify only one caption per table. Usually the caption will be centered above the table.
Source Output
<table border="1"> This is a caption
<caption>This is a caption</caption> Cell 1 Cell 2
<tr> <td>Cell 1</td> <td>Cell 2</td> </tr>
</table>

Attribute Value Description DTD


Align Left,right,top,bottom How to align the caption. Deprecated. Use styles instead. TF

<thead> tag:
10
[PROF.M.N.DESHMUKH] Mentor Classes

Defines a table header.The thead, tfoot and tbody elements enables to group rows in a table. When you create a
table, you might want to have a header row, some rows with data, and a row with totals at bottom. This division enables
browsers to support scrolling of table bodies independently of the table header and footer. When long tables are printed,
the table header and footer information may be repeated on each page that contains table data.
The <thead> must have a <tr> tag inside!
Note: If you use the thead, tfoot and tbody elements, you must use every element. They should appear in this order:
<thead>, <tfoot> and <tbody>, so that browsers can render the foot before receiving all the data. You must use these tags
within the table element.
Source Output
<table border = "1"> This text is in the THEAD
<thead> <tr> <td>This text is in the THEAD </td>
This text is in the TBODY
</tr> </thead>
This text is in the TFOOT
<tfoot> <tr> <td>This text is in the TFOOT</td>
</tr> </tfoot>
<tbody> <tr> <td>This text is in the TBODY </td>
</tr> </tbody></table>
<tbody> tag: Defines a table body.
<tfoot> tag: Defines a table footer.
Attributes are common for all 3 tags:
Attribute Value Description
Align Right,left,center,justify,char Defines the text alignment in cells
valign Top,middle,bottom,baseline Specifies the vertical text alignment in cells

Border Attribute:If not specified a border attribute the table will be displayed without any borders. Sometimes this
can be useful. To display a table with borders, you will have to use the border attribute:
<table border="1">
<tr> <td>Row 1, cell 1</td>
<td>Row 1, cell 2</td> </tr>
</table>

HTML Lists:HTML supports ordered, unordered and definition lists.


Tag Description
<ol> Defines an ordered list
<ul> Defines an unordered list
<li> Defines a list item
<dl> Defines a definition list
<dt> Defines a definition term
<dd> Defines a definition description
<dir> Deprecated. Use <ul> instead
<menu> Deprecated. Use <ul> instead
a) Unordered Lists:
11
[PROF.M.N.DESHMUKH] Mentor Classes

An unordered list is a list of items. The list items are marked with bullets (typically small black circles)An
unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
<ul>
<li>Coffee</li>
<li>Milk</li>
</ul>
Here is how it looks in a browser:
Coffee
Milk
Inside a list item its possible to put paragraphs, line breaks, images, links, other lists, etc.
Attribute Value Description
Type Disc,square,circle Specifies the type of the list. Deprecated. Use styles instead

Ordered Lists:
An ordered list is also a list of items. The list items are marked with numbers.An ordered list starts with
the <ol> tag. Each list item starts with the <li> tag.
<ol>
<li>Coffee</li>
<li>Milk</li>
</ol>
Here is how it looks in a browser:
Coffee
Milk
Inside a list item you can put paragraphs, line breaks, images, links, other lists, etc.
Attribute Value Description
Start start_on_number Specifies the number to start on. Deprecated. Use styles instead
Type A, a, I, i, 1 Specifies the type of the list. Deprecated. Use styles instead

HTML <li> tag:


The <li> tag defines the start of a list item. The <li> tag is used in both ordered (<ol>) and unordered lists (<ul>).
Attribute Value Description
type A, a, I, i, 1 Specifies the type of the list. Deprecated. Use styles instead
Disc,square,circle

HTML Forms and Input:


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

12
[PROF.M.N.DESHMUKH] Mentor Classes

<input>
</form>
Form Tags
Tag Description
<form> Defines a form for user input
<input> Defines an input field
<textarea> Defines a text-area (a multi-line text input control)
<label> Defines a label to a control
<fieldset> Defines a fieldset
<legend> Defines a caption for a fieldset
<select> Defines a selectable list (a drop-down box)
<optgroup> Defines an option group
<option> Defines an option in the drop-down box
<button> Defines a push button
<isindex> Deprecated. Use <input> instead

Source Output
<form action="form_action.asp" method="get"> Top of Form
First name: Mickey
First name:
<input type="text" name="fname" value="Mickey" />
<br /> Submit

<input type="submit" value="Submit" /> Bottom of Form


</form> If you click the "Submit" button, you
<p> will send your input to a new page
If you click the "Submit" button, you will send your input to a new page called called form_action.asp.
form_action.asp.
</p>

Attribute Value Description


action URL A URL that defines where to send the data when the submit button is
pushed
method get The HTTP method for sending data to the action URL. Default is get.
post method="get": This method sends the form contents in the URL: URL?
name=value&name=value. Note: If the form values contains non-ASCII
characters or exceeds 100 characters you MUST use method="post".
method="post": This method sends the form contents in the body of the
request. Note: Most browsers are unable to bookmark post requests.
name form_name Defines a unique name for the form
target _blank Where to open the target URL.

13
[PROF.M.N.DESHMUKH] Mentor Classes

_self _blank - the target URL will open in a new window


_parent _self - the target URL will open in the same frame as it was clicked
_top _parent - the target URL will open in the parent frameset
_top - the target URL will open in the full body of the window

Input: The most used form tag is the <input> tag. The type of input is specified with the type attribute. The most
commonly used input types are explained below.
The <input> tag defines the start of an input field where the user can enter data.
Attribute Value Description
Align Left,right,top,texttop Defines the alignment of text following the image.
middle,absmiddle Note: Only used with type="image"
baseline,bottom
absbottom
Alt Text Defines an alternate text for the image.
Note: Only used with type="image"
checked checked Indicates that the input element should be checked when it first loads.
Note: Used with type="checkbox" and type="radio"
Name field_name Defines a unique name for the input element.
Note: This attribute is required with type="button",
type="checkbox", type="file", type="hidden", type="image",
type="password", type="text", and type="radio"
type Button,checkbox,file Indicates the type of the input element. The default value is "text"
hidden,image,password Note: This is not a required attribute. If omitted, IE 5.5 will still
radio,reset,submit,text display a text field, but Netscape 4.7 will not.

<label> tag:Defines a label to a control. If you click the text within the label element, it is supposed to toggle the
control.
Source Output
<p>Try clicking on the text labels:</p> Try clicking on the text labels:
<form name="input" action=""> Top of Form
<input type="radio" name="rad1" id="male" />
Male
<label for="male">Male</label>
<br /> Female
<input type="radio" name="rad2" id="female" />
<label for="female">Female</label> Bottom of Form
</form>

Text Fields:Text fields are used when you want the user to type letters, numbers, etc. in a form.
<form>
First name:
<input type="text" name="firstname">
14
[PROF.M.N.DESHMUKH] Mentor Classes

<br>
Last name:
<input type="text" name="lastname">
</form>
How it looks in a browser:
Top of Form

First name:

Last name:

<textarea> tag: Defines a text-area (a multi-line text input control). A user can write text in the text-area. In a text-area
you can write an unlimited number of characters. The default font in the text-area is fixed pitch.
Source Output
<textarea rows="2" cols="20">
The cat was playing in the garden. Suddenly a dog
showed up.....
</textarea>

Radio Buttons:Radio Buttons are used when you want the user to select one of a limited number of choices.
<form>
<input type="radio" name="sex" value="male"> Male
<br>
<input type="radio" name="sex" value="female"> Female
</form>
How it looks in a browser:
Top of Form

Male

Female

Checkboxes :Checkboxes are used when you want the user to select one or more options of a limited number of
choices.
<form>
<input type="checkbox" name="bike">
I have a bike
<br>
<input type="checkbox" name="car">
I have a car
</form>
How it looks in a browser:
Top of Form

15
[PROF.M.N.DESHMUKH] Mentor Classes

I have a bike

I have a car
When the user clicks on the "Submit" button, the content of the form is sent to another file. The form's action
attribute defines the name of the file to send the content to. The file defined in the action attribute usually does something
with the received input.

<form name="input" action="html_form_action.asp" method="get">


Username:
<input type="text" name="user">
<input type="submit" value="Submit">
</form>
How it looks in a browser:
Top of Form
Submit
Username:

<select> tag: The select element creates a drop-down list.


Source
<select>
<option value ="volvo">Volvo</option> <option value ="saab">Saab</option>
<option value ="opel">Opel</option> <option value ="audi">Audi</option>
</select>

<option> tag:The option element defines an option in the drop-down list.


Note: The <option> tag can be used without any attributes, but usually need the value attribute, which indicates what is
sent to the server.Use this tag in conjunction with the select element, elsewhere it is meaningless.
Source
<select>
<option value ="volvo">Volvo</option>
<option value ="saab">Saab</option>
<option value ="opel" selected="selected">Opel</option>
<option value ="audi">Audi</option>
</select>

Attribute Value Description


Selected selected Specifies that the option should appear selected (will be displayed first in the list)
Value text Defines the value of the option to be sent to the server

16
[PROF.M.N.DESHMUKH] Mentor Classes

<button> tag:Defines a push button. Inside a button element you can put content, like text or images. This is the
difference between this element and buttons created with the input element.
Source
<button>Click Here!</button>

HTML Colors:
Color Values: Colors are defined using a hexadecimal notation for the combination of Red, Green, and Blue color values
(RGB). The lowest value that can be given to one light source is 0 (hex #00). The highest value is 255 (hex #FF).
This table shows the result of combining Red, Green, and Blue light sources:.

Color HEX Color RGB Color Names


#000000 rgb(0,0,0) Black
#FF0000 rgb(255,0,0) Red
#00FF00 rgb(0,255,0) Green
#0000FF rgb(0,0,255) Blue
#FFFF00 rgb(255,255,0) Yellow
#00FFFF rgb(0,255,255) Cyan
#FF00FF rgb(255,0,255) Magenta
#C0C0C0 rgb(192,192,192) Gray
#FFFFFF rgb(255,255,255) White

HTML Fonts: The <font> tag in HTML is deprecated. It is supposed to be removed in a future version of HTML.With
HTML code like this, you can specify both the size and the type of the browser output :
<p>
<font size="2" face="Verdana"> This is a paragraph. </font>
</p>
<p>
<font size="3" face="Times"> This is another paragraph.</font>
</p>
Font Attributes
Attribute Example Purpose
size="number" size="2" Defines the font size
size="+number" size="+1" Increases the font size
size="-number" size="-1" Decreases the font size
face="face-name" face="Times" Defines the font-name
color="color-value" color="#eeff00" Defines the font color
color="color-name" color="red" Defines the font color

1. Set the font of text:This example demonstrates how to set the font of a text.
<html>
<body>
<h1 style="font-family:verdana">A heading</h1>
<p style="font-family:courier">A paragraph</p>
</body>

17
[PROF.M.N.DESHMUKH] Mentor Classes

</html>

HTML<MARQUEE> TAG
This tag is used to create a scrolling text on HTML psge.
Attributes:
Bgcolor: To set the background color for marquee text.
Direction: To set the direction of scrolling text. Values can be- down, up, left, right.
Height: To specify the height of the area, in which text scrolls.
Width: To specify the width of the area, in which text scrolls.
Hspace: To set left margin for marquee area.
Vspace: To set top margin for marquee area.
Loop: To specify the number times the text will get displayed.
Scrollamount: To adjust the speed of scrolling, higer number means high speed scrolling.

Example:
<MARQUEE direction=left bgcolor=Turquoise height=10 hspace=20 loop=1 scrollamount=5 >
Smita’s Computer Institute
</MARQUEE>

18
[PROF.M.N.DESHMUKH] Mentor Classes

CHAP 2: CSS
What is CSS?
 CSS stands for Cascading Style Sheets
 Styles define how to display HTML elements
 Styles are normally stored in Style Sheets
 Styles were added to HTML 4.0 to solve a problem
 External Style Sheets can save you a lot of work
 External Style Sheets are stored in CSS files
 Multiple style definitions will cascade into one
As the two major browsers - Netscape and Internet Explorer - continued to add new HTML tags and attributes
(like the <font> tag and the color attribute) to the original HTML specification, it became more and more difficult to
create Web sites where the content of HTML documents was clearly separated from the document's presentation layout.
To solve this problem, the World Wide Web Consortium (W3C) - the non profit, standard setting consortium,
responsible for standardizing HTML - created STYLES in addition to HTML 4.0.
All major browsers support Cascading Style Sheets.
Syntax:
The CSS syntax is made up of three parts: a selector, a property and a value:
selector {property: value}

The selector is normally the HTML element/tag you wish to define, the property is the attribute you wish to change, and
each property can take a value. The property and value are separated by a colon, and surrounded by curly braces:

body {color: black}

Note: If the value is multiple words, put quotes around the value:
p {font-family: "sans serif"}

Note: If you wish to specify more than one property, you must separate each property with a semicolon. The example
below shows how to define a center aligned paragraph, with a red text color:

p {text-align:center;color:red}

To make the style definitions more readable, you can describe one property on each line, like this:
p
{
text-align: center;
color: black;
font-family: arial
}
Grouping
h1,h2,h3,h4,h5,h6
{
19
[PROF.M.N.DESHMUKH] Mentor Classes

color: green
}
The class Selector
p.right {text-align: right}
p.center {text-align: center}

You have to use the class attribute in your HTML document:


<p class="right">
This paragraph will be right-aligned.
</p>
<p class="center">
This paragraph will be center-aligned.
</p>

The id Selector:You can also define styles for HTML elements with the id selector. The id selector is defined as a #.The
style rule below will match the element that has an id attribute with a value of "green":
#green {color: green}
The style rule below will match the p element that has an id with a value of "para1":
p#para1
{
text-align: center;
color: red
}

How to Insert a Style Sheet?


When a browser reads a style sheet, it will format the document according to it. There are three ways of inserting a style
sheet:
A. External Style Sheet:
An external style sheet is ideal when the style is applied to many pages. With an external style sheet, you can
change the look of an entire Web site by changing one file. Each page must link to the style sheet using the <link> tag.
The <link> tag goes inside the head section:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
</head>
EX:mystyle.css
hr {color: sienna}
p {margin-left: 20px}
body {background-image: url("images/back40.gif")}
B. Internal Style Sheet:
An internal style sheet should be used when a single document has a unique style. You define internal styles in
the head section by using the <style> tag, like this:
<head>
<style type="text/css">
hr {color: sienna}
20
[PROF.M.N.DESHMUKH] Mentor Classes

p {margin-left: 20px}
body {background-image: url("images/back40.gif")}
</style>
</head>
C. Inline Styles:
An inline style loses many of the advantages of style sheets by mixing content with presentation. Use this method
sparingly, such as when a style is to be applied to a single occurrence of an element.
To use inline styles you use the style attribute in the relevant tag. The style attribute can contain any CSS
property. The example shows how to change the color and the left margin of a paragraph:
<p style="color: sienna; margin-left: 20px">
This is a paragraph
</p>

CSS Properties:
Property Description Values
background A shorthand property for setting all background-color
background properties in one declaration background-image
background-repeat background-
attachment background-position
background-attachment Sets whether a background image is fixed or scroll
scrolls with the rest of the page fixed
background-color Sets the background color of an element color-rgb
color-hex
color-name
transparent
background-image Sets an image as the background url(URL)
none
background-position Sets the starting position of a background top left,top center,top right,center left
image center center,center right
bottom left,bottom center
bottom right,x% y%
xpos ypos
background-repeat Sets if/how a background image will be repeat
repeated repeat-x
repeat-y
no-repeat

CSS Text Properties:


The CSS text properties allow you to control the appearance of text. It is possible to change the color of a text, increase
or decrease the space between characters in a text, align a text, decorate a text, indent the first line in a text, and more.
Property Description Values
color Sets the color of a text color
direction Sets the text direction ltr

21
[PROF.M.N.DESHMUKH] Mentor Classes

rtl

line-height Sets the distance between lines Normal, number, length, %


letter-spacing Increase or decrease the space between characters Normal , length
text-align Aligns the text in an element Left, right ,center, justify
text-decoration Adds decoration to text None, underline, overline ,line-through
blink
text-indent Indents the first line of text in an element Length, %
text-shadow None, color, length
text-transform Controls the letters in an element None, capitalize, uppercase, lowercase

Css Font properties:


Property Description Values
font A shorthand property for setting all of the properties for a font-style,font-variant,font-weight
font in one declaration font-size/line-height,font-family
caption,icon,menu,message-box
small-caption,status-bar
font-family A prioritized list of font family names and/or generic family family-name,
names for an element generic-family
font-size Sets the size of a font xx-small,x-small,small,medium
large,x-large,xx-large,smaller
larger,length,%
font-style Sets the style of the font Normal,italic,oblique
font-variant Displays text in a small-caps font or a normal font normal
small-caps

CSS Border Properties:


Property Description Values
border A shorthand property for setting all of the properties for the border-width,border-style
four borders in one declaration border-color
border-bottom A shorthand property for setting all of the properties for the border-bottom-width
bottom border in one declaration border-style,border-color
border-color Sets the color of the four borders, can have from one to Color
four colors
border-left A shorthand property for setting all of the properties for the border-left-width, border-style
left border in one declaration border-color
border-right A shorthand property for setting all of the properties for the border-right-width
right border in one declaration border-style, border-color
border-style Sets the style of the four borders, can have from one to four None, hidden, dotted, dashed, solid
styles double, groove, ridge, inset, outset

22
[PROF.M.N.DESHMUKH] Mentor Classes

border-top A shorthand property for setting all of the properties for the border-top-width
top border in one declaration border-style, border-color

border-width A shorthand property for setting the width of the four Thin, medium
borders in one declaration, can have from one to four thick, length
values

CSS Margin Properties:


Property Description Values
margin A shorthand property for setting the margin properties in margin-top, margin-right, margin-
one declaration bottom, margin-left
margin-bottom Sets the bottom margin of an element Auto,length, %
margin-left Sets the left margin of an element Auto, length, %
margin-right Sets the right margin of an element Auto, length, %
margin-top Sets the top margin of an element Auto, length, %

23
[PROF.M.N.DESHMUKH] Mentor Classes

CHAP3:JAVAScript
Introduction: JavaScript is used in millions of Web pages to improve the design, validate forms, detect browsers,
create cookies, and much more.JavaScript is the most popular scripting language on the internet, and works in all major
browsers, such as Internet Explorer, Mozilla, Firefox, Netscape, Opera.
What is JavaScript?
 JavaScript was designed to add interactivity to HTML pages
 JavaScript is a scripting language (a scripting language is a lightweight programming language)
 A JavaScript consists of lines of executable computer code
 A JavaScript is usually embedded directly into HTML pages
 JavaScript is an interpreted language (means that scripts execute without preliminary compilation)
 Everyone can use JavaScript without purchasing a license

Perfomance: JavaScript can be written such that the HTML files are compact and quite small. This minimizes storage
requirements on web server & download time for the client.
Data Types & Literal: JavaScript supports four primitive types of values & supports complex types such as
arrays, objects.The primitive data types are:
1) Number: Consists of integer & floating point numbers & the special Not a Number(NaN) value. Integer literal
can be represented in decimal, hexadecimal & octal form.
Ex: 33, 12.10, -35.8 etc.
2) Boolean: Consists of logical value true and false. Logical operators can be used in Boolean expressions. The
Boolean values true and false will get automatically converted into 1 and 0 when used in numerical expressions.
3) String: Consists of String values that are enclosed in single or double quotes. A string is sequence of zero or more
characters enclosed in double or single quote. If a string has to include quote character in the string it must be
preceded by the backslash (\) escape character.
Ex: “ \”Welcome\” to a webpage”
Null: consists of a single value null, which identifies a null, empty or nonexistent reference.

Variables:A variable is a "container" for information you want to store. A variable's value can change during the script.
You can refer to a variable by name to see its value or to change its value.
Rules for variable names:
1) Variable names are case sensitive
2) They must begin with a letter or the underscore character
IMPORTANT! JavaScript is case-sensitive! A variable named strname is not the same as a variable named STRNAME!
Declare a Variable:You can create a variable with the var statement:
var <var name> = some value
You can also create a variable without the var statement:
<var name> = some value
Assign a Value to a Variable
var strname = "Hege"
Assign a Value to a Variable Or like this: strname = "Hege"

24
[PROF.M.N.DESHMUKH] Mentor Classes

The variable name is on the left side of the expression and the value you want to assign to the variable is on the
right. Now the variable "strname" has the value "Hege".
Lifetime of Variables:When you declare a variable within a function, the variable can only be accessed within that
function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have
local variables with the same name in different functions, because each is recognized only by the function in which it is
declared.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 are declared, and ends when the page is closed.
Example:<HTML><HEAD><SCRIPT language="JavaScript">
var name=prompt("enter name", "name");
</SCRIPT></HEAD>
<BODY><SCRIPT language="JavaScript">
document.write ("<H2> Hello "+name+"</H2>");
</SCRIPT></BODY></HTML>
Examples: How to Put a JavaScript Into an HTML Page
<html><body><script type="text/javascript">
document.write("Hello World!")
</script></body></html>
output :Hello World!

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

JavaScript If...Else Statements: Conditional statements in JavaScript are used to perform different actions based on
different conditions.Very often when you write code, you want to perform different actions for different decisions. You
can use conditional statements in your code to do this.In JavaScript we have the following conditional statements:
if statement - use this statement if you want to execute some code only if a specified condition is true
if...else statement - use this statement if you want 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 if you want to select one of many blocks of code to be executed

Syntax:if (condition)
{ code to be executed if condition is true }

Example 1
<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>
If...else Statement:To execute some code if a condition is true and another code if the condition is not true, use the
if....else statement.
Syntax:

25
[PROF.M.N.DESHMUKH] Mentor Classes

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!")
}
else
{
document.write("Good day!")
}
</script>
If...else if...else Statement: Use the if....else if...else statement if you want to select one of many sets of lines to execute.
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 andcondition2 are not true
}
Example
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>")
}

26
[PROF.M.N.DESHMUKH] Mentor Classes

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


{
document.write("<b>Good day</b>")
}
else
{
document.write("<b>Hello World!</b>")
}
</script>
JavaScript Switch Statement: Conditional statements in JavaScript are used to perform different actions based on
different conditions.Use the switch statement if you want to select one of many blocks of code to be executed.
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
}
Example
<script type="text/javascript">
//You will receive a different greeting based on what day it is. Note that //Sunday=0, Monday=1, Tuesday=2, etc.
var d=new Date()
theDay=d.getDay()
switch (theDay)
{
case 5:
document.write("Finally Friday")
break
case 6:
document.write("Super Saturday")
break
case 0:
document.write("Sleepy Sunday")
break
default:
document.write("I'm looking forward to this weekend!")
}</script>
JavaScript Loops:Very often when you write code, you want the same block of code to run over and over again in a row.
Instead of adding several almost equal lines in a script we can use loops to perform a task like this.

27
[PROF.M.N.DESHMUKH] Mentor Classes

In JavaScript there are two different kind of loops:


for - loops through a block of code a specified number of times
while - loops through a block of code while a specified 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 (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}
Example
<html><body><script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
document.write("The number is " + i)
document.write("<br />")
}
</script></body></html>
Result
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10
The while loop:use when you want the loop to execute and continue executing while the specified condition is true.
while (var<=endvalue)
{
code to be executed
}
Example: To display numbers from 1 to 10.
<html><body><script type="text/javascript">
var i=0
while (i<=10)
{
document.write("The number is " + i)
document.write("<br />")
i=i+1
}
</script></body></html>

28
[PROF.M.N.DESHMUKH] Mentor Classes

The do...while Loop:The do...while loop is a variant of the while loop. This loop will always execute a block of code
ONCE, and then it will repeat the loop as long as the specified condition is true. This loop will always be executed at least
once, even if the condition is false, because the code is executed before the condition is tested.
do
{
code to be executed
}
while (var<=endvalue)
Example
<html><body><script type="text/javascript">
var i=0
do
{
document.write("The number is " + i)
document.write("<br />")
i=i+1
}
while (i<0)
</script></body></html>
Result: The number is 0
JavaScript break and continue Statements:
The break command will break the loop and continue executing the code that follows after the loop (if any).
Example<html><body><script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3) {break}
document.write("The number is " + i)
document.write("<br />")
}
</script></body></html>
Result
The number is 0
The number is 1
The number is 2
The continue command 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 />")
}
</script></body></html>

29
[PROF.M.N.DESHMUKH] Mentor Classes

Result
The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

JavaScript Popup Boxes


In JavaScript we can create three kind of popup boxes: Alert box, Confirm box, and Prompt box.
Alert BoxAn 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")
Confirm BoxA confirm box is often used if you want the user to verify or accept something. When a confirm box pops
up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user
clicks "Cancel", the box returns false.
Syntax:confirm("sometext")
Prompt BoxA prompt box is often used if you want the user to input a value before entering a page. When a prompt box
pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks
"OK" the box returns the input value. If the user clicks "Cancel" the box returns null.
Syntax:prompt("sometext","defaultvalue")

Comments:You can add comments to your script by using two slashes //:
//this is a comment
document.write("Hello World!")
or by using /* and */ (this creates a multi-line comment block):
/* This is a comment block. It contains
several lines */
document.write("Hello World!")
JavaScript Functions:To keep the browser from executing a script as soon as the page is loaded, you can write your
script as a function. A function contains some code that will be executed only by an event or by a call to that function.Its
possible to call a function from anywhere within the page (or even from other pages if the function is embedded in an
external .js file).Functions are defined at the beginning of a page, in the <head> section.
Example<html><head><script type="text/javascript">
function displaymessage()
{
alert("Hello World!")
}
</script></head><body><form>
<input type="button" value="Click me!" onclick="displaymessage()" >
</form></body></html>

30
[PROF.M.N.DESHMUKH] Mentor Classes

If the line: alert("Hello world!!"), in the example above had not been written within a function, it would have been
executed as soon as the line was loaded. Now, the script is not executed before the user hits the button. We have added an
onClick event to the button that will execute the function displaymessage() when the button is clicked.
How to Define a Function(syntax )
function functionname(var1,var2,...,varX)
{
some code
}
var1, var2, etc are variables or values passed into the function. The { and the } defines the start and end of the function.
Note: A function with no parameters must include the parentheses () after the function name:
function functionname()
{
some code
}
Note: The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you
must call a function with the exact same capitals as in the function name.
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.
Example:function prod(a,b)
{
x=a*b
return x
}
When you call the function above, you must pass along two parameters:
product=prod(2,3)
The returned value from the prod() function is 6, and it will be stored in the variable called product.
Rules for declaring a user defined function are:A function name is case sensitive, can include underscore and has to
start with a letter.A list of parameters (arguments) that will accept values passes to the function when called. The
arguments must be separated by comma.
<HTML><HEAD><SCRIPT LANGUAGE="JavaScript">
var name=""
function hello()
{
name=prompt("enter your name","name");
alert("greetings:"+name);
}
function goodbye()
{
alert("goodbye"+name)
}
</script></HEAD><body onLoad="hello();" onunUnload="goodbye();">
Example of javascript functions.
</body></HTML>
Document Object Model (DOM):An HTML page is rendered in a browser. The browser assembles all elements (objects)
contained in HTML page, downloaded from web server, in its memory. Once the page is rendered, browser can no longer

31
[PROF.M.N.DESHMUKH] Mentor Classes

recognize individual HTML elements. JavaScript enabled browsers are capable of recognizing individual objects in an
HTML page, because they use DOM.The HTML objects which belongs to DOM, have a descending relationship with
each other.The topmost object in DOM is ‘Navigator’ (Browser), the next level is browsers window, and then the
document displayed in the window.

Navigator
Window
Event
History
Location
Document
Anchor
Link
Form
Text box, text area, radio buttons, check box, select, button etc.
1. Navigator: To access information about browser that is excutting current script.
Properties:
appName: Name of application in which page is loaded.
appVersion: Version of current browser as a string.
appCodeName: Codename of current browser.
userAgent: The user agent for current browser as a string.
Example:<HTML> <HEAD><SCRIPT LANGUAGE="JavaScript">
document.write(navigator.appName+"<br>");
document.write(navigator.appVersion+"<br>");
document.write(navigator.appCodeName+"<br>");
document.write(navigator.userAgent+"<br>");
</script></HEAD> </HTML>
2. Window: To access a browser window or frame within the window.
Properties:
frames: Array of objects containing an entry for each frame in a frameset.
parent: Frameset in a Frameset-frame relation.
self: Current Window.
status: status bar.
Methods:
alert() , confirm(), prompt(), open(), close(), setTimeOut(), clearTimeOut()

3. Document: To access a document currently loaded in a window.


Methods:
open(): To open a document window.
close(): To close a document window.
clear(): To clear a document window.
write() & writeLine()

32
[PROF.M.N.DESHMUKH] Mentor Classes

4. Location: To represent URL. Used to create a URL obj., Access parts of URL, or to create a URL.
Properties:
hash: Anchor name
host: Host name
href: Entire URL
pathname: File path
port: Port number of URL.
prototcol: Protocol part of URL.
Methods:
assign(): Sets location href.
toString(): Returns location href as a string.

5. History: To maintain the history of URL’s accessed in window.


Property:
Length: length of history list.
Methods:
back(): Loads previous URL in history list.
forward(): Loads next URL in history list.
go(): URL indicated by an offset from current place.
-ve to go back.
+ve to go forward.
6. Event: Provides constants that are used to identify events.
7. Screen: To access information about size, color depth of client computers screen in which the current browser is
running.
JavaScript has number of Event Handlers.JavaScript event handlers, can be divided into 2 types:
1. Interactive: Depends on user interaction with HTML page. Ex: onMouseOver…etc.
2. Non-Interactive: Doesn’t need user interaction to be invoked Ex: onLoad, onUnload… etc
JavaScript event handlers
onAbort: Loading of image is aborted due to user interaction
OnBlur: A document, window, frameset or a form element loses current input focus.
onChange: A text field, text area, file uploaded field or selection is modified &loses current
input focus.
onClick: A button, link, client-side image map area or document is clicked.
onDblClick: A button, link, client-side image map area or document is clicked.
onDragDrop: A dragged object is dropped in a window or frame.
onError: An error occurs during loading of an image, window or frame.
onFocus: A document, window, frameset or form element receives input focus.
onKeyDown: The user presses a key
onKeyPress: The user presses & releases a key.
onKeyUp: The user releases a key
onLoad: An image, document or frameset is loaded.
onMouseDown: The user presses a mouse button.
onMouseMove: The user moves a mouse.
onMouseOut: The mouse is moved out of alink or image map area.
onMouseOver: The mouse is moved over of alink or image map area.
onMouseUp: The user releases a mouse button.
onReset: The user resets a form by clicking on forms reset button.
33
[PROF.M.N.DESHMUKH] Mentor Classes

onResize: The user resizes a window or frame.


onSelect: Text is selected in textfield or text area.
onSubmit: User presses a form’s submit button.
onUnload: The user exits from a document or frameset.
CHAP 4:VBScript
What is VBScript?
 VBScript is a scripting language
 A scripting language is a lightweight programming language
 VBScript is a light version of Microsoft's programming language Visual Basic

How Does it Work?


When a VBScript is inserted into a HTML document, the Internet browser will read the HTML and interpret the
VBScript. The VBScript can be executed immediately, or at a later event.

How to Put VBScript Code in an HTML Document


<html>
<body>
<script type="text/vbscript">
document.write("Hello from VBScript!")
</script>
</body>
</html>
output: Hello from VBScript!
To insert a script in an HTML document, use the <script> tag. Use the type attribute to define the scripting language.

Where to Put the VBScript?


Scripts in a page will be executed immediately while the page loads into the browser. This is not always what we
want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event.

1) Scripts in the head section: Scripts to be executed when they are called or when an event is triggered go in the
head section. When you place a script in the head section you will assure that the script is loaded before anyone
uses it:
<html> <head>
<script type="text/vbscript">
some statements
</script> </head>
2) Scripts in the body section: Scripts to be executed when the page loads go in the body section. When you place a
script in the body section it generates the content of the page:
<html>
<body>
<script type="text/vbscript">
some statements
</script>
</body>
3) Scripts in both the body and the head section: You can place an unlimited number of scripts in your document,
so you can have scripts in both the body and the head section.
<html>
34
[PROF.M.N.DESHMUKH] Mentor Classes

<head>
<script type="text/vbscript">
some statements
</script>
</head>
<body>
<script type="text/vbscript">
some statements
</script>
</body>

What is a Variable?A variable is a "container" for information you want to store. A variable's value can change during
the script. You can refer to a variable by name to see its value or to change its value. In VBScript, all variables are of type
variant, that can store different types of data.
Rules for Variable Names:
" Must begin with a letter
" Cannot contain a period (.)
" Cannot exceed 255 characters

Declaring Variables:To declare variables with the Dim, Public or the Private statement. Like this:
dim name
name=some value

Option Explicit: use this statement when to declare all variables with the dim, public or private statement.
Put the Option Explicit statement on the top of your script. Like this:
option explicit
dim name
name=some value

Assigning Values to Variables:You assign a value to a variable like this:


Name="Hege"
i=200
The variable name is on the left side of the expression and the value you want to assign to the variable is on the right.
Now the variable "name" has the value "Hege".

Lifetime of Variables: How long a variable exists is its lifetime. When a variable is declared within a procedure, the
variable can only be accessed within that procedure. When the procedure exits, the variable is destroyed. These variables
are called local variables. You can have local variables with the same name in different procedures, because each is
recognized only by the procedure in which it is declared.
If declare a variable outside a procedure, all the procedures on your page can access it. The lifetime of these
variables starts when they are declared, and ends when the page is closed.

Array Variables: To assign more than one value to a single variable. This is called an array variable. The declaration of
an array variable uses parentheses ( ) following the variable name. In the following example, an array containing 3
elements is declared: dim names(2).The number shown in the parentheses is 2. We start at zero so this array contains 3
elements. This is a fixed-size array. You assign data to each of the elements of the array like this:
35
[PROF.M.N.DESHMUKH] Mentor Classes

names(0)="Tove"
names(1)="Jani"
names(2)="Stale"
An array can have up to 60 dimensions. Multiple dimensions are declared by separating the numbers in the
parentheses with commas. Here we have a two-dimensional array consisting of 5 rows and 7 columns:
dim table(4, 6)

VBScript Procedures:There are two kinds of procedures: The Sub procedure and the Function procedure.
Sub procedure:is a series of statements, enclosed by the Sub and End Sub statements can perform actions, but does not
return a value can take arguments that are passed to it by a calling procedure without arguments, must include an empty
set of parentheses ()
Sub mysub()
some statements
End Sub
or
Sub mysub(argument1,argument2)
some statements
End Sub

Function procedure:is a series of statements, enclosed by the Function and End Function statements can perform actions
and can return a value can take arguments that are passed to it by a calling procedure without arguments, must include an
empty set of parentheses () returns a value by assigning a value to its name
Function myfunction()
some statements
myfunction=some value
End Function
or
Function myfunction(argument1,argument2)
some statements
myfunction=some value
End Function

Call a Sub or Function Procedure


name = findname()
Here call a Function called "findname", the Function returns a value that will be stored in the variable "name".
Or, you can do like this: msgbox "Your name is " & findname()

When call a Sub procedure use the Call statement, like this:
Call MyProc(argument)
Or,
MyProc argument

Conditional Statements: To perform different actions for different decisions use conditional statements .In VBScript we
have three conditional statements:

36
[PROF.M.N.DESHMUKH] Mentor Classes

If....Then.....Else: use the If...Then...Else statement if want to execute some code if a condition is true select one of two
blocks of code to execute

To execute more than one statement when a condition is true, must put each statement on separate lines and end the
statement with the keyword "End If":
if i=10 Then
msgbox "Hello"
i = i+1
end If

There is no ..else.. in this syntax either. You just tell the code to perform multiple actions if the condition is true.
To execute a statement if a condition is true and execute another statement if the condition is not true, must add the "Else"
keyword:
If i=10 then
msgbox "Hello"
else
msgbox "Goodbye"
end If
If....Then.....Elseif:Use the if...then...elseif statement to select one of many blocks of code to execute:
if payment="Cash" then
msgbox "You are going to pay cash!"
elseif payment="Visa" then
msgbox "You are going to pay with visa."
elseif payment="AmEx" then
msgbox "You are going to pay with American Express."
else
msgbox "Unknown method of payment."
end If

Select Case;
You can also use the SELECT statement if you want to select one of many blocks of code to execute:
case "Cash"
msgbox "You are going to pay cash"
case "Visa"
msgbox "You are going to pay with visa"
case "AmEx"
msgbox "You are going to pay with American Express"
case Else
msgbox "Unknown method of payment"
end select

Looping Statements:Used to allow the same block of code to run a number of times. use looping statements.In VBScript
we have four looping statements:
For...Next statement - runs statements a specified number of times.
For Each...Next statement - runs statements for each item in a collection or each element of an array

37
[PROF.M.N.DESHMUKH] Mentor Classes

Do...Loop statement - loops while or until a condition is true


While...Wend statement - Do not use it - use the Do...Loop statement instead

For...Next Loop:Use a For...Next statement to run a block of code, when you know how many repetitions you want.
For i=1 to 10
some code
Next
The For statement specifies the counter variable (i) and its start and end values. The Next statement increases the counter
variable (i) by one.
Using the Step keyword, you can increase or decrease the counter variable by the value you specify.
For i=2 To 10 Step 2
some code
Next
To decrease the counter variable, you must use a negative Step value. You must specify an end value that is less than the
start value.
For i=10 To 2 Step -2
some code
Next
For Each...Next Loop:A For Each...Next loop repeats a block of code for each item in a collection, or for each element
of an array.
dim cars(2)
cars(0)="Volvo"
cars(1)="Saab"
cars(2)="BMW"

For Each x in cars


document.write(x & "<br />")
Next
Do...Loop:Use Do...Loop to run a block of code when you do not know how many repetitions you want. The block of
code is repeated while a condition is true or until a condition becomes true. Repeating Code While a Condition is True
Do While i>10
some code
Loop
If i equals 9, the code inside the loop above will never be executed.
Do
some code
Loop While i>10
The code inside this loop will be executed at least one time, even if i is less than 10. Repeating Code Until a Condition
Becomes True You use the Until keyword to check a condition in a Do...Loop statement.
Do Until i=10
some code
Loop
If i equals 10, the code inside the loop will never be executed.
Do
some code

38
[PROF.M.N.DESHMUKH] Mentor Classes

Loop Until i=10


The code inside this loop will be executed at least one time, even if i is equal to 10.
Exit a Do...Loop
You can exit a Do...Loop statement with the Exit Do keyword.
Do Until i=10
i=i-1
If i<10 Then Exit Do
Loop
The code inside this loop will be executed as long as i is different from 10, and as long as i is greater than 10.

Error Handling & Debugging:


Dealing with errors actually involves two different processes: Error handling & Debugging.
Error Handling: is a combination of coding & methodology that allows your program to anticipate user & other errors.
Debugging: Involves finding errors & removing them from a program.
Errors or Bugs can be of two types:
Syntax Errors:
Wrong spellings.
Any kind of typographical & syntactical mistakes
Logical Errors:
Although Syntactically correct, program either doesn’t function well as per expectations.

Errors can appear at 2 different times:At compile time & at runtime.


On Error Resume Next:Remarks Enables error-handling.If you don't use an On Error Resume Next statement, any run-
time error that occurs is fatal; that is, an error message is displayed and execution stops.
On Error Resume Next causes execution to continue with the statement immediately following the statement that caused
the run-time error, or with the statement immediately following the most recent call out of the procedure containing the
On Error Resume Next statement. This allows execution to continue despite a run-time error. You can then build the error-
handling routine inline within the procedure. An On Error Resume Next statement becomes inactive when another
procedure is called, so you should execute an On Error Resume Next statement in each called routine if you want inline
error handling within that routine. The following example illustrates use of the On Error Resume Next statement:
Dim x,y,z
On Error Resume Next
x=10
y=0
z=x/y
If Err.Number<>0 then
MsgBox(“Error Number:”&Err.Number&”Description:”&Err.Description)
Else
MsgBox z
End If

Built In Functions:
A. Date & Time Functions:
1. Cdate()- The CDate function converts a valid date and time expression to type Date, and returns the result.
Use the IsDate() function to determine if date can be converted to a date or time.
Syntax: CDate(date)
39
[PROF.M.N.DESHMUKH] Mentor Classes

Parameter date is Required. It can be any valid date expression (like Date() or Now())
Example 1
d="April 22, 2001"
if IsDate(d) then
document.write(CDate(d))
end if

2. Date()- The Date function returns the current system date.


Syntax: Date()
Example 1
document.write("The current system date is: ")
document.write(Date)

3. DateAdd()- The DateAdd function returns a date to which a specified time interval has been added.
Syntax: DateAdd (interval,number,date)
Parameter:
Interval: Required. The interval needs to add.Can take the following values:
yyyy – Year, q – Quarter, m – Month, y - Day of year
d – Day, w – Weekday, ww - Week of year
h – Hour, n – Minute, s – Second
Number: Required. The number of interval wants to add. Can either be positive, for dates in the future, or negative, for
dates in the past
Date : Required. Variant or literal representing the date to which interval is added
Example 1
'Add one month to January 31, 2000
document.write(DateAdd("m",1,"31-Jan-00"))
Output: 2/29/2000

4. DateDiff()- The DateDiff function returns the number of intervals between two dates.
Syntax: DateDiff(interval,date1,date2[,firstdayofweek[,firstweekofyear]])
date1,date2 : Required. Date expressions. Two dates to use in the calculation
firstdayofweek : Optional. Specifies the day of the week. Can take the following values:
1 = vbSunday - Sunday (default), 2 = vbMonday - Monday
3 = vbTuesday – Tuesday, 4 = vbWednesday - Wednesday
5 = vbThursday – Thursday, 6 = vbFriday - Friday
7 = vbSaturday – Saturday
firstweekofyear : Optional. Specifies the first week of the year. Can take the following values:
1 = vbFirstJan1 - Start with the week in which January 1 occurs (default)
2 = vbFirstFourDays - Start with the week that has at least four days in the new year
3 = vbFirstFullWeek - Start with the first full week of the new year
Example 1
document.write(Date & "<br />")
document.write(DateDiff("m",Date,"12/31/2002") & "<br />")
document.write(DateDiff("d",Date,"12/31/2002") & "<br />")
document.write(DateDiff("n",Date,"12/31/2002"))

40
[PROF.M.N.DESHMUKH] Mentor Classes

5. DateValue()- The DateValue function returns a type Date.


Note: If the year part of date is omitted this function will use the current year from the computer's system date.
Syntax : DateValue(date)
Example 1
document.write(DateValue("31-Jan-02") & "<br />")
document.write(DateValue("31-Jan") & "<br />")
document.write(DateValue("31-Jan-02 2:39:49 AM"))

6. Day()- The Day function returns a number between 1 and 31 that represents the day of the month.
Syntax: Day(date)
Example 1
document.write(Date & "<br />")
document.write(Day(Date))

7. Hour()- The Hour function returns a number between 0 and 23 that represents the hour of the day.
Syntax: Hour(time)
Example 1
document.write(Now & "<br />")
document.write(Hour(Now))

8. Month()- The Month function returns a number between 1 and 12 that represents the month of the year.
Syntax: Month(date)
Example 1
document.write(Date & "<br />")
document.write(Month(Date))
9. Now()- The Now function returns the current date and time according to the setting of your computer's system
date and time.
Syntax: Now()
Example 1
document.write(Now)
10. Time()- The Time function returns the current system time.
Syntax: Time()

11. Weekday()- The Weekday function returns a number between 1 and 7, that represents the day of the week.
Syntax: Weekday(date[,firstdayofweek])
Example 1
document.write(Date & "<br />")
document.write(Weekday(Date))

String Functions:
1. InStr () - The InStr function returns the position of the first occurrence of one string within another.
Syntax: InStr([start,]string1,string2)
Parameter Description
Start Optional. Specifies the starting position for each search. The search begins at the first character position
by default. This parameter is required if compare is specified
string1 Required. The string to be searched
41
[PROF.M.N.DESHMUKH] Mentor Classes

string2 Required. The string expression to search for

Example 1
dim txt,pos
txt="This is a beautiful day!"
pos=InStr(txt,"his")
document.write(pos)
Output: 2

2. LCase() - The LCase function converts a specified string to lowercase. Syntax : LCase(string)
Example 1
dim txt
txt="THIS IS A BEAUTIFUL DAY!"
document.write(LCase(txt))
Output: this is a beautiful day!

3. Left ()- The Left function returns a specified number of characters from the left side of a string.
Syntax: Left(string,length)
Example 1
dim txt
txt="This is a beautiful day!"
document.write(Left(txt,11))
Output: This is a b

4. Len()- The Len function returns the number of characters in a string. Syntax: Len(string|varname)
Example 1
dim txt
txt="This is a beautiful day!"
document.write(Len(txt))
Output: 24

5. LTrim() - The LTrim function removes spaces on the left side of a string. Syntax: LTrim(string)
Example 1
dim txt
txt=" This is a beautiful day! "
document.write(LTrim(txt))
Output: "This is a beautiful day! "

6. RTrim ()- The RTrim function removes spaces on the right side of a string. Syntax: RTrim(string)
Example 1
dim txt
txt=" This is a beautiful day! "
document.write(RTrim(txt))
Output: " This is a beautiful day!"

7. Trim()- The Trim function removes spaces on both sides of a string. Syntax: Trim(string)
42
[PROF.M.N.DESHMUKH] Mentor Classes

Example 1
dim txt
txt=" This is a beautiful day! "
document.write(Trim(txt))
Output: "This is a beautiful day!"

8. Mid ()- The Mid function returns a specified number of characters from a string.
Syntax: Mid(string, start[,length])
Parameter Description
string Required. The string expression from which characters are returned
start Required. Specifies the starting position. If set to greater than the number of characters in string, it
returns an empty string ("")
length Optional. The number of characters to return
Example 2
dim txt
txt="This is a beautiful day!"
document.write(Mid(txt,10))
Output: beautiful day!

9. Replace()- The Replace function replaces a specified part of a string with another string a specified number of
times.Syntax: Replace(string,find,replacewith[,start[,count]])
Parameter Description
string Required. The string to be searched
find Required. The part of the string that will be replaced
replacewith Required. The replacement substring
start Optional. Specifies the start position. Default is 1
count Optional. Specifies the number of substitutions to perform. Default value is -1, which means make all
possible substitutions
Example 1
dim txt
txt="This is a beautiful day!"
document.write(Replace(txt,"beautiful","horrible"))
Output: This is a horrible day!

10. StrComp()- The StrComp function compares two strings and returns a value that represents the result of the
comparison.The StrComp function can return one of the following values:
-1 (if string1 < string2)
0 (if string1 = string2)
1 (if string1 > string2)
Null (if string1 or string2 is Null)
Syntax: StrComp(string1,string2)
Example 1
document.write(StrComp("VBScript","VBScript"))

43
[PROF.M.N.DESHMUKH] Mentor Classes

Math Functions:
1. Abs()- The Abs function returns the absolute value of a specified number.
Note: If the number parameter contains Null, Null will be returned. If the number parameter is an uninitialized
variable, zero will be returned. Syntax: Abs(number)
Example 1
document.write(Abs(1) & "<br />")
document.write(Abs(-1))
Output:
1
1

2. Exp()- The Exp function returns e raised to a power. Note: The value of number cannot exceed 709.782712893.
Syntax: Exp(number)
Example 1
document.write(Exp(6.7))
Output: 812.405825167543

3. Hex()- The Hex function returns a string that represents the hexadecimal value of a specified number.Note: If
number is not a whole number, it is rounded to the nearest whole number before being evaluated. Syntax: Hex
(number)
Parameter Description
Number Required. Any valid expression
If number is:
Null - then the Hex function returns Null.
Empty - then the Hex function returns zero (0).
Any other number - then the Hex function returns up to eight hexadecimal characters.
Example 1
document.write(Hex(3) & "<br />")
document.write(Hex(460))
Output: 3
1CC

4. Log()- The Log function returns the natural logarithm of a specified number. The natural logarithm is the
logarithm to the base e.
Note: Negative values are not allowed.
Syntax: Log(number)
Example 1
document.write(Log(38.256783227))
Output: 3.64432088381777

5. Sgn()- The Sgn function returns an integer that indicates the sign of a specified number.Syntax: Sgn(number)
44
[PROF.M.N.DESHMUKH] Mentor Classes

Parameter Description
Number Required. A valid numeric expression
If number is:
>0 - Sgn returns 1
=0 - Sgn returns 0
<0 - Sgn returns -1

6. Sin()- The Sin function returns the sine of a specified number (angle).Syntax: Sin(number)
Example 1
document.write(Sin(47))
Output: 0.123573122745224

7. Sqr()- The Sqr function returns the square root of a number.Note: The number parameter cannot be a negative
value.Syntax: Sqr(number)
Example 1
document.write(Sqr(9))
Output: 3

Other Functions:
1. InputBox()- The InputBox function displays a dialog box, where the user can write some input and/or click on a
button. If the user clicks the OK button or presses ENTER on the keyboard, the InputBox function will return the text in
the text box. If the user clicks on the Cancel button, the function will return an empty string ("").
Syntax :InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])
Example 1
dim fname
fname=InputBox("Enter your name:")
MsgBox("Your name is " & fname)

2. MsgBox ()- The MsgBox function displays a message box, waits for the user to click a button, and returns a value that
indicates which button the user clicked.
The MsgBox function can return one of the following values:
1 = vbOK - OK was clicked
2 = vbCancel - Cancel was clicked
3 = vbAbort - Abort was clicked
4 = vbRetry - Retry was clicked
5 = vbIgnore - Ignore was clicked
6 = vbYes - Yes was clicked
7 = vbNo - No was clicked
Note: The user can press F1 to view the Help topic when both the helpfile and the context parameter are specified.
Syntax: MsgBox(prompt[,buttons][,title][,helpfile,context])
Example 1
dim ans wer
answer=MsgBox("Hello everyone!",65,"Example")
document.write(answer)

45
[PROF.M.N.DESHMUKH] Mentor Classes

CHAP 5: XML
What Is XML?
XML stands for Extensible Markup Language XML is a set of rules for defining semantic tags that break a
document into parts and identify the different parts of the document. It is a meta-markup language that defines a syntax in
which other field-specific markup languages can be written. XML means you don’t have to wait for browser vendors to
catch up with what you want to do. You can invent the tags you need, when you need them, and tell the browsers how to
display these tags.
XML describes structure and semantics, not formatting
The second thing to understand about XML is that XML markup describes a document’s structure and meaning. It
does not describe the formatting of the elements on the page. Formatting can be added to a document with a style sheet.
The document itself only contains tags that say what is in the document, not what the document looks like.

Features of XML:
1. XML makes easy many Web-development tasks that are extremely difficult with HTML, and it makes tasks that are
impossible with HTML, possible. Because XML is extensible, developers like it for many reasons. Which reasons most
interest you depends on your individual needs; but once you learn XML, you’re likely to discover that it’s the solution to
more than one problem you’re already struggling with. This section investigates some of the generic uses of XML that
excite developers.
2. Design of field-specific markup languages:XML enables individual professions (e.g., music, chemistry, human
resources) to develop their own field-specific markup languages. These languages make it possible for practitioners in the
field to trade notes, data, and information without worrying about whether or not the person on the receiving end has the
particular proprietary payware that was used to create the data.
3. Self-describing data:Furthermore, XML is very well documented. The World Wide Web Consortium (W3C)’s XML
1.0 specification and numerous paper books like this one tell you exactly how to read XML data.
4. Interchange of data among applications:Because XML is nonproprietary and easy to read and write, it’s an excellent
format for the interchange of data among different applications. XML is not encumbered by copyright, patent, trade secret,
or any other sort of intellectual property restrictions.It has been designed to be extremely powerful, while at the same time
be easy for both human beings and computer programs to read and write. Thus it’s an obvious choice for exchange
languages.
5. Structured and integrated data:XML is ideal for large and complex documents because the data is structured. It not
only lets you specify a vocabulary that defines the elements in the document; it also lets you specify the relations between
elements.

The Life of an XML Document:


XML is, at its root, a document format. It is a series of rules about what XML documents look like. There are two
levels of conformity to the XML standard. The first is well-formedness and the second is validity.
However, like all data formats, XML needs programs and content before it’s useful. Thus, it isn’t enough to just
understand XML itself. That’s not much more than a specification for what data should look like. You also need to know
how XML documents are created, written, and edited, how processors read XML documents and pass the information they
read on to applications, and what these applications do with that data.

Editors:XML documents are most commonly created with an editor. This may be a basic text editor such as Notepad or vi
that doesn’t really understand XML at all. On the other hand, it may be a completely WYSIWYG (What You See Is What
You Get) editor such as Adobe FrameMaker that insulates you almost completely from the details of the underlying XML

46
[PROF.M.N.DESHMUKH] Mentor Classes

format. Or it may be a structured editor such as Visual XML (http://www.pierlou.com/visxml/) that displays XML
documents as trees.
Parsers and processors:An XML parser (also known as an XML processor) reads the document and verifies that the
XML it contains is well formed. It may also check that the document is valid, although this test is not required. If the
document passes the tests, then the processor converts the document into a tree of elements.

Browsers and other applications:Finally, the parser passes the tree or individual nodes of the tree to the end application.
If this application is a Web browser such as Mozilla, then the browser formats the data and shows it to the user. But other
programs may also receive the data. XML is extremely flexible and can be used for many different purposes.
The process summarized
To summarize, an XML document is created in an editor. The XML parser reads the document and converts it into a tree
of elements. The parser passes the tree to the browser or other application that displays it. Figure 1-1 shows this process.

Creating a simple XML document


<?xml version=”1.0”?>
<GREETING> Hello XML! <GREETING>
The first line of the simple XML document in Listing 3-1 is the XML declaration:
<?xml version=”1.0”?>
The XML declaration has a version attribute. An attribute is a name-value pair separated by an equals sign. The
name is on the left side of the equals sign, and the value is on the right side between double quote marks.
Every XML document should begin with an XML declaration that specifies the version of XML in use. In the previous
example, the version attribute says that this document conforms to the XML 1.0 specification.

Organization of XML data:XML is based on a containment model. Each XML element can contain text or other XML
elements called children. A few XML elements may contain both text and child elements. This is called mixed content.

The Advantages of the XML Format


 The data is self-describing.
 The data can be manipulated with standard tools.
 The data can be viewed with standard tools.
 Different views of the same data are easy to create with style sheets.

Attributes:As in HTML, XML elements may have attributes. An attribute is a name-value pair associated with an
element. The name and the value are each strings. Must always be quoted and start tags must have matching end tags. For
example, instead of containing a YEAR child element, the SEASON element only needs a YEAR attribute:
<SEASON YEAR=”1998”> </SEASON>
Anytime there’s likely to be more than one of something, child elements are called for. XML elements can
conveniently encode structure. Attribute values cannot.

47
[PROF.M.N.DESHMUKH] Mentor Classes

Attributes versus Elements


 Attributes can’t hold structure well. Elements can have substructure, attributes can’t.
 Elements allow you to include meta-metadata (information about the informationabout the information).
 Not everyone always agrees on what is and isn’t metadata.
 Elements are more extensible in the face of future changes. Attributes are certainly convenient when you only
need to convey one or two words of unstructured information. In these cases, there may genuinely be no current
need for a child element. However, this doesn’t preclude such a need in the future.

Entities:XML documents are made up of storage units called entities. Each entity contains either text or binary data,
never both. Text data is comprised of characters. Binary data is used for images and applets and the like.

The XML declaration:The documents only contain text data, not binary data such as images or applets. Such documents
can be understood completely on their own without reading any other files. In other words, they stand alone. Such a
document normally contains a standalone pseudo-attribute in its XML declaration with the value yes, similar to this one.
<?xml version=”1.0” standalone=”yes”?>
If a document does not have an XML declaration, or if a document has an XML declaration but that XML declaration
does not have a standalone pseudo-attribute, then the value no is assumed.
A document must have exactly one root element that completely contains all other elements.
An XML document has a root element that completely contains all other elements of the document. This is also
sometimes called the document element, although this element does not have to have the name document or root. Root
elements are delimited by a start tag and an end tag, just like any other element.

Text in XML:An XML document is made up of text. Text is made up of characters. A character is a letter, a digit, a
punctuation mark, a space or tab, or some similar thing. XML uses the Unicode character set which not only includes the
usual letters and symbols from English and other Western European alphabets, but also the Cyrillic, Greek, Hebrew,
Arabic, and Devanagari alphabets, as well as the most common Hanideographs for Chinese, Japanese, and Korean Hangul
syllables. For now, markup includes all tags, processing instructions, DTDs, entity references, character references,
comments, CDATA section delimiters, and the XML declaration. Everything else is character data. However, this is tricky
because when a document is processed some of the markup turns into character data. For example, the markup &gt; is
turned into the greater than sign character (>).
The character data that’s left after the document is processed, and after all markup that refers to character data has been
replaced by the actual character data, is called parsed character data, or PCDATA for short.

Elements and Tags:An XML document is a singly rooted hierarchical structure of elements. Each element is delimited by
a start tag (also known as an opening tag) and an end tag (also known as a closing tag) or is represented by a single, empty
element tag. An XML tag has the same form as an HTML tag. That is, start tags begin with a < followed by the name of
the element the tags start, and they end with the first > after the opening < (for example, <GREETING>). End tags begin
with a </ followed by the name of the element the tag finishes and are terminated by a > (for example, </GREETING>).
Empty element tags begin with a < followed by the name of the element and are terminated with a /> (for example,
<GREETING/>).

Element names:Every element has a name made up of one or more characters. This is the name included in the element’s
start and end tags.
 Element names begin with a letter such as y or A or an underscore _.
 Subsequent characters in the name may include letters, digits, underscores, hyphens, and periods.
 They cannot include other punctuation marks such as %, ^, or &.

48
[PROF.M.N.DESHMUKH] Mentor Classes

 They cannot include white space. (The underscore often substitutes for white space.)
 Both lower- and uppercase letters may be used in XML names.

Every start tag must have a corresponding end tag:Web browsers are relatively forgiving if you forget to close an
HTML tag. For instance, if you include a <B> tag in your document but no corresponding </B> tag, the entire document
after the <B> tag will be made bold. However, the document will still be displayed.
XML is not so forgiving. Every nonempty tag—that is, tags that do not end with />—must be closed with the
corresponding end tag. If a document fails to close an element with the right end tag, the browser or renderer reports an
error message and does not display any of the document’s content in any form.
Empty element tags:Elements that are represented by a single tag without a closing tag are called empty elements
because they have no content. Tags that represent empty elements are called empty-element tags. These empty element
tags are closed with a slash and a closing angle bracket (/>); for example, <BR/> or <HR/>.

Attributes
Elements may optionally have attributes. Each attribute of an element is encoded in the start tag of the element as a name-
value pair separated by an equals sign (=) and, optionally, some extra white space. The attribute value is enclosed in single
or double quotes.
For example,
<GREETING LANGUAGE=”English”>
Hello XML!
<MOVIE SRC = ‘WavingHand.mov’/>
</GREETING>

Attribute names:Attribute names are strings that follow the same rules as element names. That is, attribute names must
contain one or more characters, and the first character must be a letter or the underscore (_). Subsequent characters in the
name may include letters, digits, underscores, hyphens, and periods. They may not include white space or other
punctuation marks.The same element may not have two attributes with the same name. For example, this is illegal:
<RECTANGLE SIDE=”8” SIDE=”10”/>
Attribute names are case sensitive. The SIDE attribute is not the same as the side or the Side attribute. Therefore, the
following is legal:
<BOX SIDE=”8” side=”10” Side=”31”/>

Processing Instructions:Processing instructions are like comments that are intended for computer programs reading the
document rather than people reading the document.
Processing instructions begin with <? and end with ?>. The starting <? is followed by an XML name called the target,
which identifies the program that the instruction is intended for, followed by data for that program.
<?xml-stylesheet type=”text/xml” href=”5-2.xsl”?>

CDATA Sections:Suppose your document contains one or more large blocks of text that have a lot of <, >, &, or “
characters but no markup. This would be true for a Java or HTML tutorial, for example. It would be inconvenient to have
to replace each instance of one of these characters with the equivalent entity reference. Instead, you can include the block
of text in a CDATA section.
CDATA sections begin with <![CDATA[ and end with ]]>. For example:
<![CDATA[
System.out.print(“<”);
if (x <= args.length && y > z) { System.out.println(args[x - y]);
49
[PROF.M.N.DESHMUKH] Mentor Classes

}
System.out.println(“>”); ]]>

Document Type Defination (DTD) :A document type definition lists the elements, attributes, entities, and notations that
can be used in a document, as well as their possible relationships to one another.
A DTD specifies a set of rules for the structure of a document.Every valid XML document must specify DTD its
valid with respect to.Can be in XML document it describes or that document can link to it at external URL.Such DTDs
can be shared by different documents & websites.The real power of XML comes from common DTDs that are shared
among many documents written by different people.
DTDs provide a means for applications, organizations, and interest groups to agree upon, document, & enforce
adherence to markup standards.The DTD defines exactly what is and is not allowed to appear inside a document.A DTD
shows the generic structure of a document separate from the actual data in the individual document instances.
Element Declarations
<?xml version=”1.0”?>
<GREETING>
Hello XML!
</GREETING>
Elements are declared using element declarations. Each element declaration gives the name of the element and lists the
elements and text that it can contain. This list is called the content model. For instance, this element declaration for the
GREETING element says that elements with name GREETING must contain only parsed character data:
<!ELEMENT GREETING (#PCDATA)>
Thus, a document type declaration has this basic form:
<!DOCTYPE name_of_root_element
SYSTEM “URL of the external DTD subset” [
internal DTD subset
]>
Here name_of_root_element is simply the name of the root element. The SYSTEM keyword indicates that what follows is
a URL where the DTD is located. The square brackets enclose the internal subset of the DTD—that is, those declarations
included inside the document itself. You can omit either the SYSTEM keyword and the URL to the external DTD subset
or the square brackets and internal DTD subset.
For example, this document type declaration only specifies an external DTD that can be found at the URL
http://ibiblio.org/greeting.dtd:
<!DOCTYPE GREETING SYSTEM “…/greeting.dtd”>
This document type declaration includes the DTD inside itself:
<!DOCTYPE GREETING [<!ELEMENT GREETING (#PCDATA)>]>

Internal DTDs
<?xml version=”1.0”?>
<!DOCTYPE GREETING [<!ELEMENT GREETING (#PCDATA)>]>
<GREETING>
Hello XML!
</GREETING>

A document whose DTD has both an internal and an external subset

50
[PROF.M.N.DESHMUKH] Mentor Classes

<?xml version=”1.0”?>
<!DOCTYPE DOCUMENT SYSTEM “greeting.dtd” [
<!ELEMENT DOCUMENT (GREETING, DATE)>
<!ELEMENT DATE (#PCDATA)>
]>
<DOCUMENT>
<GREETING>Hello</GREETING>
<DATE>July 28, 2000</DATE>
</DOCUMENT>
Validating Against a DTD
To be considered valid, an XML document must satisfy four criteria:
1. It must be well formed.
2. It must have a document type declaration.
3. Its root element must be the one specified by the document type declaration.
4. It must satisfy all the constraints indicated by the DTD specified by the document type declaration.
This document is invalid because it does not satisfy the DTD’s rules
<?xml version=”1.0”?>
<!DOCTYPE GREETING SYSTEM “greeting.dtd”>
<FOO>
Hello XML!
</FOO>

This document has two problems:


1. The root element is not GREETING as required by the document type
declaration.
2. The FOO element has not been declared.

Example: demo.css
SEASON {font-size: 24pt; background-color: white; color: black; display: block}
YEAR {font-size: 20pt; background-color: white; color: BLUE; display: block}
COUNTRY {font-size: 22pt; background-color: white; color: black; display: block}
COUNTRY_NAME {font-size: 20pt; background-color: white; color: blue; display: block}

demo.dtd
<!ELEMENT SEASON ANY>
<!ELEMENT YEAR (#PCDATA)>
<!ELEMENT COUNTRY (COUNTRY_NAME)>
<!ELEMENT COUNTRY_NAME (#PCDATA)>

demo.xml
<?xml version=”1.0” ?>
<?xml-stylesheet type=text/css href=”demo.css” ?>
<!DOCTYPE SEASON SYSTEM “demo.dtd”>
<SEASON>
<YEAR>1998</YEAR>

51
[PROF.M.N.DESHMUKH] Mentor Classes

<COUNTRY>
COUNTRY_NAME> America <COUNTRY_NAME>
</COUNTRY>
</SEASON>

Attribute Declarations:Declare attributes in DTD with:


<!ATLIST ELEMENT-NAME ATTRIBUTE-NAME TYPE DEFAULTVALUE>
<GREETING LANG=”English”>
Hello!
</GREETING>
IN DTD can be written as:
<!ELEMENT GREETING (#PCDATA)>
<!ATLIST GREETING LANG CDATA “English”>
Entity Declarations:A single XML document may draw both data & declarations from many different sources, in many
different sites. The items where the pieces of an XML document are stored, in whatever form they take, are called entities.
Entity references load these entities into the main XML document.
Entity references begins with a & and ends with ;
Example of General Entity reference:
<?xml version="1.0"?>
<!DOCTYPE DOCUMENT[
<!ENTITY MSG "The authors info">
<!ELEMENT DOCUMENT (TITLE,SIGN)>
<!ELEMENT TITLE (#PCDATA)>
<!ELEMENT SIGN (COPYRIGHT,EMAIL)>
<!ELEMENT COPYRIGHT (#PCDATA)>
<!ELEMENT EMAIL (#PCDATA)>]>
<DOCUMENT>
<TITLE>&MSG;</TITLE>
<SIGN>
<COPYRIGHT>2005 &MSG;</COPYRIGHT>
<EMAIL>ABC@XYZ.COM</EMAIL>
</SIGN>
check is A&lt;B
</DOCUMENT>

XML Schema:XML Schema is an XML based alternative to DTD.An XML schema describes the structure of an XML
document.The XML Schema language is also referred to as XML Schema Definition (XSD).The purpose of an XML
Schema is to define the legal building blocks of an XML document, just like a DTD.
An XML Schema:
 defines elements that can appear in a document
 defines attributes that can appear in a document
 defines which elements are child elements
 defines the order of child elements
 defines the number of child elements
 defines whether an element is empty or can include text
 defines data types for elements and attributes
52
[PROF.M.N.DESHMUKH] Mentor Classes

 defines default and fixed values for elements and attributes


XML Schemas are the Successors of DTDs:We think that very soon XML Schemas will be used in most Web
applications as a replacement for DTDs. Here are some reasons:
 XML Schemas are extensible to future additions
 XML Schemas are richer and more useful than DTDs
 XML Schemas are written in XML
 XML Schemas support data types
 XML Schemas support namespaces
XML Schema has Support for Data Types:One of the greatest strengths of XML Schemas is the support for data
types.With the support for data types:
 It is easier to describe permissible document content
 It is easier to validate the correctness of data
 It is easier to work with data from a database
 It is easier to define data facets (restrictions on data)
 It is easier to define data patterns (data formats)
 It is easier to convert data between different data types
XML Schemas are Extensible:XML Schemas are extensible, just like XML, because they are written in XML.With an
extensible Schema definition you can:
 Reuse your Schema in other Schemas
 Create your own data types derived from standard types
 Reference multiple schemas from the same document
 XML documents can have a reference to a DTD or an XML Schema.
A Simple XML Document:Look at this simple XML document called "note.xml":
<?xml version="1.0"?>
<note>
<to>abc</to>
<from>xyz</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
A Simple DTD:This is a simple DTD file called "note.dtd" that defines the elements of the XML document above
("note.xml"):
<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
Line 1 defines the note element to have four elements: "to, from, heading, body". Line 2-5 defines the ‘to’ element to be of
the type "#PCDATA", the ‘from’ element to be of the type "#PCDATA", and so on...
A Simple XML Schema:This is a simple XML Schema file called "note.xsd" that defines the elements of the XML
document above ("note.xml"):
<?xml version="1.0"?>
<xs:schema xmlns:xs=”http://www.w3.org/2001/XMLSchema” elementFormDefault="qualified">
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>

53
[PROF.M.N.DESHMUKH] Mentor Classes

<xs:element name="from" type="xs:string"/>


<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The <schema> Element:The <schema> element is the root element of every XML Schema:
xmlns:xs="http://www.w3.org/2001/XMLSchema"
indicates that the elements and data types used in the schema (schema, element, complexType, sequence, string, boolean,
etc.) come from the "http://www.w3.org/2001/XMLSchema" namespace. It also specifies that the elements and data types
that come from the "http://www.w3.org/2001/XMLSchema" namespace should be prefixed with xs: !!

What is a Simple Element?A simple element is an XML element that can contain only text. It cannot contain any other
elements or attributes.However, the "only text" restriction is quite misleading. The text can be of many different types. It
can be one of the types that are included in the XML Schema definition (boolean, string, date, etc.), or it can be a custom
type that you can define yourself.You can also add restrictions (facets) to a data type in order to limit its content, and you
can require the data to match a defined pattern.
The syntax for defining a simple element is:
<xs:element name="xxx" type="yyy"/>
where xxx is the name of the element and yyy is the data type of the element.
Common XML Schema Data Types:It has a lot of built-in data types. Here is a list of the most common types:
xs:string
xs:decimal
xs:integer
xs:boolean
xs:date
xs:time
SAX vs. DOM
There are no hard and fast rules to specify when to use one parser API over another; however, circumstances may
dictate when one might work better than another.All SAX processing is done in a single pass; so, SAX generally offers a
performance advantage over DOM when parsing equivalently sized documents, because DOM must perform tree
traversals.Further, because only part of an XML document need be in memory at a given time, SAX is usually more
memory-efficient with larger documents than DOM is (as I've mentioned, DOM must load an entire XML document into
memory before beginning to parse it).
On the downside, SAX applications often sport long, complicated if/else constructs to determine what action to
take when a particular element is processed.
Similarly, dealing with data structures that have been spread between multiple XML elements is challenging with
SAX because of intermediate data that must be stored between parsing events.
Finally, the event-handling structure of a SAX application usually means that SAX applications are custom-built for a
specific document structure, whereas DOM applications can be much more generalised.
Many languages, like Python and all the .NET languages, have built-in support for SAX in their core functionality.

54
[PROF.M.N.DESHMUKH] Mentor Classes

CHAP 6: ASP- Microsoft Active Server Pages

Developed by Microsoft in 16-July-1996 as a powerful & easy technology to create dynamic web pages. Simple
to use & extensible. You can combine HTML pages, scripts & activex components to create interactive web pages. Allows
you to generate the browser-neutral contents using server side scripting.
The key component of ASP is a dedicated web server. ASP provides better communication between browser &
server with release of Internet Information Server (IIS 4.0) & Personal Web Server (PWS). ASP page is any file located on
web server that has extension .asp. When ASP page has been requested, before sending a page to users browser, it is
processed by web server. It interprets and executes any scripts in ASP page before sending it to users browser.
Understanding client-server model
Client – Requests the resources.
Server – Provides the resources.
Types of web pages – static & dynamic.
When web browser requests an ASP, it follows steps-
1. the client/web browser locates the web server specified by first part of URL.
2. Client requests a ASP page.
3. Server reads the ASP file & process code.
4. Server returns HTML format to client.
ASP vs. Client Side Scripting
The 2 types of scripting are –
Client side – the over use of client side scripting can result in large files that take a long time to download. Runs or
executed on browser. Reduces work of server & network traffic. Is commonly written using JavaScript because Netscape
Navigator only supports this for client-side scripting.
Server Side- Requires because the need for active web sites. The benefits are –
1. Protects the code
2. Enables web application to access database.
The page contents can be retrieved from database, text files & other data sources. Then can be inserted using HTML code
dynamically before displayed to users.
Allows to develop web application such that change in HTML design doesn’t affect the programs that retrieve data from
database. Changing data sources will not require to change HTML document.
Use this when access to data that resides anywhere except client.
To differentiate where ASP code starts & ends <% %> tags are used.
1. Request object: Collections:
a. Form - The Form collection is used to retrieve the values of form elements from a form that uses the
POST method .If you want to post large amounts of data (beyond 100 kb) the Request.Form cannot be used. Syntax -
Request. Form (element)[(index)|. Count]
Parameter Description
element Required. The name of the form element from which the collection is to retrieve values
index Optional. Specifies one of multiple values for a parameter. From 1 to Request.Form (parameter).
Count.
Examples:youcan loop through all the values in a form request. If a user filled out a form by specifying two values - Blue
and Green - for the color element, you could retrieve those values like this:

<%
55
[PROF.M.N.DESHMUKH] Mentor Classes

for i=1 to Request.Form("color").Count


Response.Write(Request.Form("color")(i) & "<br />")
Next %>
Output: Blue
Green
b. querystring: The QueryString collection is used to retrieve the variable values in the HTTP query string.The HTTP
query string is specified by the values following the question mark (?), like this:
<a href= "test.asp?txt=this is a query string test">Link with a query string</a>
The line above generates a variable named txt with the value "this is a query string test".Query strings are also generated
by form submission, or by a user typing a query into the address bar of the browser.
Syntax - Request.QueryString(variable)[(index)|.Count]
Parameter Description
variable Required. The name of the variable in the HTTP query string to retrieve
Index Optional. Specifies one of multiple values for a variable. From 1 to
Request.QuerString(variable).Count

2. Cookies – Uses to store information on a customers computer when customer visit your web site. You can
use this information to identify customer once again, whenever customer returns to your site. You can store visitors
username, preferences like favorite product, place etc.Two types of cookies are-
1. Session - stored in memory & remains on customers computer only while customer is visiting your web site.
2. Persistent- can last many months or years. Stored in text file on customers computer called Cookie file.
In Netscape all persistent cookies from all web sites will get stores in “cookies.txt” file under /Netscape or
/Netscape/user/username folder. Ms-Internet Explorer creates a separate cookie file for each web site located in
/windows/cookies folder. A web site can read only the cookies it has set.
Cookies are not reliable because –
1. Privacy worries- User can disabled cookies from browser
2. Cookies files can be deleted or corrupted.
3. Visitor may access website from a machine that is different from where the cookies was placed.
Limitations of Cookies-
1. A single computer can hold maximum 300 cookies from all web sites.
2. Single website cann’t add more than 20 cookies to customers computer.
3. An individual cookie cannot hold data more than 4kb.
A cookie can be simple or complex.
-Simple cookie contains a single value.
Ex- value=Request.Cookies(“”username”)
-Complex – contains more than one value within a single cookie.
Ex- un=Request.Cookies(“user”)(“username”)
upass=Request.Cookies(“user”)(“userpass”)

- To check whether the cookie is simple or complex use HasKeys which returns true or false.
If Request.cookies(“user”).HasKeys then
Response.write “complex”
Else
Response.write “Simple”

56
[PROF.M.N.DESHMUKH] Mentor Classes

End if
3. Response ObjectThe ASP Response object is used to send output to the user from the server. Its
collections, properties, and methods are described below:

Examples Global.asa:
<script language="vbscript" runat="server">
Sub Application_OnEnd()
Application("totvisitors")=Application("visitors")
End Sub
Sub Application_OnStart
Application("visitors")=0
End Sub
Sub Session_OnStart
Application.Lock
Application("visitors")=Application("visitors")+1
Application.UnLock
End Sub
Sub Session_OnEnd
Application.Lock
Application("visitors")=Application("visitors")-1
Application.UnLock
End Sub
</script>
To display the number of current visitors in an ASP file:
<html> <body>
<p> There are <%response.write(Application("visitors"))%> online now! </p>
</body> </html>

4. Session object:The Session object is used to store information about, or change settings for a user session.
Variables stored in the Session object hold information about one single user, and are available to all pages in one
application.When you are working with an application, you open it, do some changes and then you close it.
This is much like a Session. The computer knows who you are. It knows when you start the application and when
you end. But on the Internet there is one problem: the web server does not know who you are and what you do because
the HTTP address doesn't maintain state. ASP solves this problem by creating a unique cookie for each user. The cookie
is sent to the client and it contains information that identifies the user. This interface is called the Session object.
The Session object is used to store information about, or change settings for a user session. Variables stored in the
Session object hold information about one single user, and are available to all pages in one application. Common
information stored in session variables are name, id, and preferences. The server creates a new Session object for each
new user, and destroys the Session object when the session expires.

<% Session("name")="Hege"
Set Session("objtest")=Server. CreateObject("ADODB.Connection")%>
Example
To loop through the Contents collection:
<%for each x in Session.Contents
Response.Write(x & "=" & Session.Contents(x) & "<br />")
Next %>
57
[PROF.M.N.DESHMUKH] Mentor Classes

or:
<% For i=1 to Session.Contents.Count
Response.Write(i & "=" & Session.Contents(i) & "<br />")
Next %>
Example
<%
Session("name")="Hege"
Session("date")="2001/05/05"
for each x in Session.Contents
Response.Write(x & "=" & Session.Contents(x) & "<br />")
next
%>
Output:
name=Hege
date=2001/05/05

Using Database:A database is a collection of organized data, which can be queried & modified. Database can be
connected to ASP pages with help of Activex Data Objects (ADOs), component written by Microsoft.
The Open Database Connectivity (ODBC) standard, provides a common interface to a database so that same coed will
work regardless of what database we are using.
1.Connection object –

Contains variety of properties & methods for connecting to a database & to manage the behavior of that connection is
created using CreateObject method of Server object.
Ex – set con = Server.CreateObject (“adodb.connection”)
Properties
1. ConnectionString- if you want connection without using DSN, we can supply a connect string that specifies all
information ADO needs to connect to db.
con.ConnectionString=ConnectStringText
In this with driver specify server name, user name, password, name of db in server etc.
Ex- Con.ConnectionString=”provider=microfsoft.jet.OLEDB.4.0; DataSource=’\..\project.mdb’”
Con.open
2. Provider – indicates db service used to connect to db Provider=con.provider
3. state – indicates whether connection is opened or closed. 1- open, 0-closed. Value=con.state

Methods:Allows you to open & manage connections-


1. BeginTrans – Indicates that you want to start a transaction
con.BeginTrans
2. CommitTrans – Changes are made to db from buffer
con.CommitTrans
3. RollBackTrans – discards any changes in buffer that are made within scope of current transaction.
Con.RollBackTrans
4. Close – Provides mechanism for disconnecting a connection object from a db.
Con.close
5. Open – used to open a connection to db.
Con.open DSN, username, password, options.
58
[PROF.M.N.DESHMUKH] Mentor Classes

6. Execute – runs a query, stored procedure or some other db functions. Can return nothing or may return
recordset.

2. RecordSet object: Used to browse through data returned from Execute method of Connection object.
fsEx- set rs = con.execute (“select * from emp”)
There are 3 regions of recordset – BOF, records, EOF
If r.s has no records, record pointer will be pointed to both BOF & EOF
Properties :A page is one or more records & that division is carried out through all records in recordset.
So if page size is 4 & you have 25 records then you have 7 pages of data.
To handle pages 3 properties are –
1. ActiveConnection – to retrieve information about how connection was made.
Coninfo=rs.ActiveConnection
2. BOF – Reports you, whether you are on beginning of file region.
3. EOF - Reports you, whether you are at end of file region.
Methods –
1. Open – used to open a record set. The form of open method is -
RS.open SQLText, ConnectString, CursorType, LockType, Options
[ Options is an optional parameter that tells the provider how to evaluate source parameter – the values are –
1. adCmdText- indicates that the provider should evaluate source as a textual definition of command.
2. adCmdTale – provider should evaluate source as table name.
3. adCmdStoredProc – source as a stored procedure

3.ADO Command Object


: The ADO Command object is used to submit and execute a specific (single) query against a database.
The query can command a variety of actions, such as adding, creating, deleting, retrieving, or updating databases (record
sets).
Code:
Set objCommand.ActiveConnection =
"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=test.mdb"
or
objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=test.mdb"
Set objCommand.ActiveConnection = objConnecion

Example:
<%
set conn=server.createobject(“adodb.connection”)
conn.open “mydsn”
set cmd=server.createobject(“adodb.command”)
set cmd.activeconnection=conn
cmd.commandtext=“select count(empid) as cnt from emp where deptno=1”
set rs=cmd.execute
Response.write “total number of employees working in dept 1 are” & rs(“cnt”)
%>

59
[PROF.M.N.DESHMUKH] Mentor Classes

The Global.asa file:The Global.asa file is an optional file that can contain declarations of objects, variables, and methods
that can be accessed by every page in an ASP application. All valid browser scripts (JavaScript, VBScript, JScript,
PerlScript, etc.) can be used within Global.asa. The Global.asa file can contain only the following:
 Application events
 Session events
<object> declarations
TypeLibrary declarations
the #include directive

Note: The Global.asa file must be stored in the root directory of the ASP application, and each application can only have
one Global.asa file.

Events in Global.asa: In Global.asa you can tell the application and session objects what to do when the
application/session starts and what to do when the application/session ends. The code for this is placed in event handlers.
The Global.asa file can contain four types of events:
I. Application_OnStart - This event occurs when the FIRST user calls the first page from an ASP application. This
event occurs after the Web server is restarted or after the Global.asa file is edited. The "Session_OnStart" event
occurs immediately after this event.
II. Session_OnStart - This event occurs EVERY time a NEW user requests his or her first page in the ASP
application.
III. Session_OnEnd - This event occurs EVERY time a user ends a session. A user ends a session after a page has not
been requested by the user for a specified time (by default this is 20 minutes).
IV. Application_OnEnd - This event occurs after the LAST user has ended the session. Typically, this event occurs
when a Web server stops. This procedure is used to clean up settings after the Application stops, like delete
records or write information to text files.
A Global.asa file could look something like this:
<script language="vbscript" runat="server">
sub Application_OnStart
''''some code
end sub
sub Application_OnEnd
''''some code
end sub
sub Session_OnStart
''''some code
end sub
sub Session_OnEnd
''''some code
end sub
</script>
Note: We cannot use the ASP script delimiters (<% and %>) to insert scripts in the Global.asa file, we will have to put the
subroutines inside the HTML <script> tag.

Restrictions: Restrictions on what you can include in the Global.asa file: You can not displ y text that is written in the
Global.asa file. This file can't display information. You can only use Server and Application objects in the
Application_OnStart and Application_OnEnd subroutines. In the Session_OnEnd subroutine, you can use Server,
Application, and Session objects. In the Session_OnStart subroutine you can use any built-in object
60
[PROF.M.N.DESHMUKH] Mentor Classes

Global.asa Example : In this example we will create a Global.asa file that counts the number of current visitors.
The Application_OnStart sets the Application variable "visitors" to 0 when the server starts
The Session_OnStart subroutine adds one to the variable "visitors" every time a new visitor arrives
The Session_OnEnd subroutine subtracts one from "visitors" each time this subroutine is triggered
The Global.asa file:
<script language="vbscript" runat="server">
Sub Application_OnStart
Application("visitors")=0
End Sub
Sub Session_OnStart
Application.Lock
Application("visitors")=Application("visitors")+1
Application.UnLock
End Sub
Sub Session_OnEnd
Application.Lock
Application("visitors")=Application("visitors")-1
Application.UnLock
End Sub
</script>
To display the number of current visitors in an ASP file:
<html><body><p>There are <%response.write(Application("visitors"))%>
online now! </p> </body> </html>

61

You might also like