You are on page 1of 76

What is the Internet ?

™In 1969 *ARPAnet - A four-computers network was Established


by US Defence Agency for Research Scientists Communication
*Some books refer call it as DARPAnet

™In 1980 it consisted of more than 200 hundred sites

™In 1983 CERN, the European Practicle Physics Laboratory,


released HTML(Hyper Text Markup Language)

™In 1990 ARPAnet was turned into the so-called Internet.

™Evolution of ISP’s(Internet Service Providers)

™ISP Gateways used to route business and commerce data over the
Internet.

Web Programming
Shahbaz Pervez
World Wide Web
™WWW is a service of the Intenet

™WWW is a vast collection of information that is spread across hundreds of


thousands of computers around the world.

™The World Wide Web is a network of thousands of computers, all of which fall
neatly into two categories: clients and servers.

™Servers store information and process requests from clients. Servers also send
instructions to the client on how to display all this information. These instructions
are sent in the form of Hypertext Markup Language (HTML).

™Clients make requests for information. Web browser acts as a client.

™Users navigate the World Wide Web through the use of hypertext links.

™Most of the documents on the World Wide Web are written in Hypertext
Markup Language (HTML). HTML provides instructions for the client software
Web Programming
on how the document should be displayed. Shahbaz Pervez
Communication on The Internet and
Domain Name Resolution
™TCP/IP is the only protocol used to send data all around the Internet.

™TCP is a set of communication protocols and IP is a unique address.

™ InterNIC is responsible for allocating unique IP to ISP’s.

™IP address points to an actual computer connected via gateway to Internet.

This computer is known as a ‘Domain’ (a place where information is available). This

is a ‘Physical Domain’ on the Internet.

™The Web Site which provides information to the client is mounted as a

‘Virtual Domain’ on an Internet Server, which is its host (Physical Domain).

™Multiple Virtual Domains hosted on a single Physical Domain


Web Programming
Shahbaz Pervez
Domain Name Extension

.edu Servers that provide Educational services


.gov Provide Information about the governments
.mil Provide Military information
.org Provide information on organisations in the World
.com Provide commercial services on the Internet

Web Programming
Shahbaz Pervez
Uniform Resource Locators (URLs).
™URLs are used by Web browsers to locate and access information on the

World Wide Web. Think of URLs as postal addresses for the Internet.

™The first part of the URL is known as the protocol. This is almost always

http://, which is short for Hypertext Transfer Protocol. Some URLs start with

a different protocol, such as ftp:// or news://. If you're accessing a document

on your local machine instead of on the Web, the URL will begin with file://.

™The second part of the URL is known as the domain name.

™The third part of the URL is called the directory path.

™The fourth part of the URL is called the document file name.

Web Programming
Shahbaz Pervez
Web Browser and Web Server
™Your Web browser is your gateway to the World Wide Web. A browser is
the client software that allows you to access and view any document on the
Web. There are a number of Web browsers that you can use to access the
Web, and the number of choices available grows every month. For example
Internet Explorer, Netscape Navigator, Neo Planet etc.

™When an Internet client connects to an Internet Server some software


running on the Internet Server must respond to the client’s request for
information. This software is called the ‘Web Server’.

™The examples of Web Servers are IIS, PWS, Apache, Orielly etc etc.

Web Programming
Shahbaz Pervez
About HTML
HTML isn't the only way to present information on the Web, but it's the glue that holds everything
together. In addition to being a markup language for displaying text, images, and multimedia, HTML
provides instructions to Web browsers in order to control how documents are viewed and how they
relate to each other. For all its simplicity, HTML is a very powerful language.

Without HTML, the World Wide Web wouldn't exist. HTML allows the individual elements on the
Web to be brought together and presented as a collection. Text, images, multimedia, and other files can
all be packaged together using HTML.

There are many ways you can use HTML to publish content on the World Wide Web. For instance:-

1. You can create a personal home page


2. You can create a page for your company to advertise and promote products and services.
3. You can build a catalog on the World Wide Web, complete with product descriptions and photographs.
You can even incorporate fill-in order forms so that your customers can order products from you on
line.
4. You can create a searchable phone directory for your company or organization.
5. You can teach people how to dissect a frog.
6. You can create a newsletter on the Web, with pictures and sounds. Using some of the advanced HTML
tricks explained in this book, you can format the newsletter to give it a slick, professional appearance.

Web Programming
Shahbaz Pervez
Writing First Page
The use of markup tags is what separates HTML from plain old text. Markup tags are used extensively
in HTML, and they provide ways to control text formatting, create links to other documents, and even
incorporate images and sounds. In short, markup tags are the key to making HTML pages work.

To create a web page:-


1. Open a new document in Notepad and type <HTML>. To begin the head section, insert an opening tag
into your HTML document by typing <HEAD>. The only element required in the head section is the
Title of your document. Your title should be short enough to fit in the title bar of a typical browser
window, but descriptive enough to explain what your HTML document contains. Insert a title tag within
the head section by typing <TITLE>, followed by the actual title of your document. In this example,
we'll name this document HTML: Easier Than We Thought. Go ahead and type in that title, then close
the tag by typing </TITLE> on the same line. Close the head section by typing </HEAD> on the line
below the title line.

2. The body section of your HTML document contains most of the text, graphics, hypertext links, and
other information that will appear on the page. All of your HTML formatting tags, which describe the
content and appearance of your document, are placed in the body section. T
Sometimes it's easier to type both the <BODY> and </BODY> tags on separate lines right away, and
then fill in the rest of your HTML document between them.
Insert the opening body tag by typing <BODY> on a new line in your document. Following the
<BODY> tag, begin entering the actual text of your HTML document. For this example, we'll just
insert a simple sentence. Type HTML is much easier than I thought. Close the body section of your
document by typing </BODY> on a new line. Make sure that this closing tag appears before the
</HTML> tag at the very bottom of your document. Web Programming
Shahbaz Pervez
Open your favourite editor and type in the following code

<HTML>
<HEAD>
<TITLE>MY FIRST PAGE</TITLE>
</HEAD>
<BODY>
HTML is much easier than I thought
</BODY>
</HTML>

Web Programming
Shahbaz Pervez
HTML TAGS

Tag Attributes
<HTML>…</HTML>

<HEAD>…
</HEAD>
<TITLE>…
</TITLE>
<BODY>…</BODY> Background, Bgproperties=fixed Bgcolor,Text,
Link,Alink,Vlink , Leftmargin,

Web Programming
Shahbaz Pervez
HTML TAGS
Tag Attributes
<I>…</I>
<B>…</B>
<U>…</U>
<P>….</P> ALIGN=
“center/left/right”
<h1>…</h1>
</h2>…</h2>
.
</h6>
<HR>….</HR> Align=left/right/center
Size=no of pixels
Width=no of pixels
Web Programming
Shahbaz Pervez
HTML TAGS
Tag Attributes
<BR>…</BR> Clear=left/right/center
<CITE>…</CITE>
<CODE>..</CODE>
<DFN>…</DFN>
<EM>…</EM>

<SAMP>..</SAMP>
<STRONG>…
</STRONG>
<KBD>…</KBD>

Web Programming
Shahbaz Pervez
HTML TAGS
Tag Attributes
<BLINK>…
</BLINK>
<STRIKE>…
</STRIKE>
<SUB>…</SUB>
<SUP>…</SUP>
<BASEFONT> Size=1/2/3/4/5/6/7
<FONT>…</FONT> Size, Color, Face
<PRE>…</PRE> Width
<CENTER>..</CENTER>

Web Programming
Shahbaz Pervez
HTML TAGS
Tag Attributes
<IMG> Align,Alt,Border,Controls,Dynsrc,
Height,Loop,Src,Lowsrc,Width,
Hspace,Vspace
<BGSOUND> Src, Loop
<MARQUEE> Align=top/middle/bottom,
Behavior=scroll/slide/alternate,
Bgcolor, Direction, Height,
Hspace, Loop,
Scrollamount, Scrolldelay,
Vspcace, Width
<A>….</A> Href, Name, Target

Web Programming
Shahbaz Pervez
Adding Lists to A Page

Unordered Lists Sample Output


<body> My Online Books Store
•Computers Books
<b>My Online Books Store</b>
•Medicine Books
<UL> •Arts Books
<LI>Computers Books
<LI>Medicine Books
<LI>Arts Books
</UL>
</body>

<UL Type=“dis/circle,square”>
Web Programming
Shahbaz Pervez
Emded Unordered Lists Sample Output
<body> My Online Books Store
•Computers Books
<b>My Online Books Store</b>
oHardWare Books
<UL> oSoftware Books
<LI>Computers Books oMisc Books
<UL> •Medicine Books
<LI>Computers Books •Arts Books
<LI>Medicine Books
<LI>Arts Books
</UL>
<LI>Medicine Books
<LI>Arts Books
</UL>
Web Programming
</body> Shahbaz Pervez
Ordered Lists Sample Output
<body> My Online Books Store
1 Computers Books
<b>My Online Books Store</b>
2 Medicine Books
<OL type=1> 3 Arts Books
<LI>Computers Books
<LI>Medicine Books
<LI>Arts Books
</UL>
</body>

Web Programming
Shahbaz Pervez
Emded Ordered Lists Sample Output
<body>

<b>My Online Books Store</b> My Online Books Store


1.Computers Books
<OL type=1> a.Software Books
<LI>Computers Books
<OL type=“a”>
b.HardWare Books
<LI>Computers Books c.Misc Books
<LI>Medicine Books 2.Medicine Books
<LI>Arts Books 3.Arts Books
</OL>
<LI>Medicine Books
<LI>Arts Books
</OL>
</body>
Web Programming
Shahbaz Pervez
Definition Lists Sample Output

<body> Keyboard
An input device
<DL> Printer
<DT>Keyboard An output device
<DD>An input device
<DT>Printer
<DD>An output device
</DL>
</body>

Web Programming
Shahbaz Pervez
<TABLE>
Attributes:
Align, Valign, Width, Border, Cellpadding, Cellspacing,
Colspan, Rowspan

<CAPTION
Align=top/bottom> ………</CAPTION>

<TR Align, Bgcolor, Bordercolor, Bordercolorlight,


Bordercolordark,Valign>………</TR>
<TH> </TH>
}
<TD> </TD> Same attributes
</TR>

Web Programming
Shahbaz Pervez
<table border="4" width="50%"
bordercolor=“GREEN" cellspacing="8"
cellpadding="4" bordercolorlight=“YELLOW"
bordercolordark=“TEAL">

<td width="50%" valign="middle" align="center"


bgcolor=“BROWN" bordercolor=“RED"
bordercolorlight=“BLUE"
bordercolordark=“MAGENTA">THIS IS TEST DATA</td>

Web Programming
Shahbaz Pervez
<tr>
<td width="50%" valign="middle"
align="center" bgcolor=“GREEN"
bordercolor=“BLACK" bordercolorlight=“TEAL"
bordercolordark=“YELLOW"
rowspan="2">TEST</td>
<td width="50%" valign="middle"
align="center" bgcolor=“BLUE"
bordercolor=“TEAL" bordercolorlight=“GREEN"
bordercolordark=“RED" colspan="2">
TEST DATA</td>
</tr>
Web Programming
Shahbaz Pervez
FRAMES
<FRAMESET>
Attributes: Rows, Cols

e.g <Frameset rows=“33%,33%,34%”>

<FRAME>
Attributes: Src=url, Marginheight, Marginwidth, Name,
Noresize, Scrolling

e.g. <Frame src=url Name=“left”>

Web Programming
Shahbaz Pervez
Frames Example
Frame.html
<Frameset Rows=“70,*”>
<Frame Src=“left.html” name=“Left”>
<Frame Src=“right.html” name=“Right”>
</Frameset>

Left.html
<b>Click the links below</b>
<a href=“test1.html” target=“Right”> Want to test this</a><br>
<a href=“test2.html” target=“Right”> Or this</a>

Right.html

Web Programming
Shahbaz Pervez
FORMS on a WEB PAGE
<FORM ACTION=URL METHOD=GET/POST>
…………
</FORM>
<INPUT>
Creates an input element within a form.
Attributes:
Align, Checked, Maxlength, Name, Size
Src, Type, Value

<Input Type=text Name=fname Size=15 Maxlength=20


Value=type In Your First Name>

<Input Type=checkbox Name=chk Value=sports Checked >

Web Programming
Shahbaz Pervez
FORMS on a WEB PAGE
<Input Type=radio Name=favourite Value=Dog Checked>
<Input Type=radio Name=favourite Value=Cat>
<Input Type=radio Name=favourite Value=Horse>
<Input Type=Submit Value=click to Submit Name=S1>
<Input Type=image Src=URL Name=img1>
<Input Type=hidden Name=action Value=change>
<TEXTAREA>
<Textarea name=txt1 cols=40 rows=10
wrap=off/physical/virtual>Some Text</Textarea>

Web Programming
Shahbaz Pervez
FORMS on a WEB PAGE

<SELECT>

Attributes: Multiple, Name, Size

<Select name=pets size=3 multiple>


<option slected>Cat
<option>Dog
<option>Horse
</Select>

Web Programming
Shahbaz Pervez
DHTML
™What is DHTML?
™Cascading Style Sheets

Syntax:

<STYLE Type=“text/css”>
Tag{attribute:value; attribute:value;………}
</STYLE>

The following attributes are used in the STYLE tag.

Font Attributes, Color Attributes, Background Attributes,


Text Attributes, Border Attributes, Margin Attributes and
List Attributes Web Programming
Shahbaz Pervez
DHTML
Using Font Attributes:
font-family, font-style, font-weight, font-size

<HTML>
<HEAD>
<TITLE>Style Sheets</TITLE>
<Style type=“text/css”>
<!-- H1{font-family:arial}
P {font-size:12pt;font-style:italic} -- >
</STYLE>
</HEAD>
<BODY>
<H1>Testing Cascading Style Sheets</H1>
<P>Now we are testing cascading style sheets and checking out its effects.
<P>There is a lot of dynamic work that we can do using CSS and
Scripting Languages
Web Programming
</BODY></HTML> Shahbaz Pervez
Using Color and Background Attributes:
Color: A color name
Background-color:Color name
Background-image:URL of image
Background-repeat:Repeat-x,Repeat-y,Repeat

H1{font-family:arial;font-size:26pt;background-image=URL(….)}

Using Text Attributes:


Text-decoration:underline,overline,line-through,blink
Vertical-align:baseline,sub,super,top,text-top,middle,bottom,text-bottom
Text-transform:capitalize,uppercase,lowercase
Text-align:left,right,center,justify
Text-indent:a number or %

Web Programming
Shahbaz Pervez
Border Attributes:
Border-style: solid,double,groove,ridge,inset,outset
Border-color: a color name
Border-width, border-top-width, border-bottom-width, border-left-width,
Border-right-width: thin,medium,thick or any length
Border-bottom, border-top, border-right:width,color
Border: sets all attributes at once

Margin Attributes:
Margin-top, margin-bottom,margin-left, margin-right, margin:
Percent,length or auto
List Attributes:
List-style-type:disc/circle/square,decimal,lower-roman,upper-
roman,lower-alpha,upper-alpha,none
Web Programming
Shahbaz Pervez
Class
<htnl>
</head>
<Style type=“text/css”>
P {font-size:12pt;font-weight:bold;text-align:justify;
margin-left:10%;margin-right:10%}
.question{color:brown; font-style:italic}
.answer {color:green}
</Style>
</head>
<body>
<P class=‘question’>Who invented Radio</P>
<P class=‘answer’>Obviously that wasn't me! Ha Ha Haaaa… </P>
<A calss=“question”>What is <Span class=“answer”>CSS</Span>
</body>
</html> Web Programming
Shahbaz Pervez
External Style Sheet
Code for mysheet.css
P {font-size:12pt;font-weight:bold;text-align:justify;
margin-left:10%;margin-right:10%}
.question{color:brown; font-style:italic}
.answer {color:green}
Code for HTML page

<HTML><HEAD>
<Link REL=stylesheet HREF=“mysheet.css”>
</HEAD>
</BODY>
</HTML>
A word on <DIV> tag Web Programming
Shahbaz Pervez
Java Script
<SCRIPT>
<!-- Begin to hide script contents from old browsers.
JavaScript statements...
// End the hiding here. -->
</SCRIPT>

Web Programming
Shahbaz Pervez
Specifying a File of JavaScript Code
The SRC attribute of the <SCRIPT> tag lets you specify a file as the JavaScript
source (rather than embedding the JavaScript in the HTML). For example:
<HEAD>
<TITLE>My Page</TITLE>
<SCRIPT SRC="common.js">
...
</SCRIPT>
</HEAD>
<BODY>
...

Web Programming
Shahbaz Pervez
<NOSCRIPT> Tag
<NOSCRIPT> is used to specify alternate content for browsers that do not support
JavaScript. The following example shows a <NOSCRIPT> tag.

<NOSCRIPT>
<B>This page uses JavaScript, so you need to get Netscape
Navigator 2.0 or later!
<BR>
If you are using Navigator 2.0 or later, and you see this
message, you should enable JavaScript by on the Advanced
page of the preferences dialog box.
</NOSCRIPT>
...

Web Programming
Shahbaz Pervez
Values, Variables, and Literals

Values
JavaScript recognizes the following types of values:
•Numbers, such as 42 or 3.14159
•Logical (Boolean) values, either true or false
•Strings, such as "Howdy!"
null, a special keyword denoting a null value
You can use the Date object and its methods to handle dates.

Variables
You use variables as symbolic names for values in your application. You give
variables names by which you refer to them and which must conform to certain
rules.
A JavaScript identifier, or name, must start with a letter or underscore ("_");
subsequent characters can also be digits (0-9). Because JavaScript is case sensitive
letters include the characters "A" through "Z" (uppercase) and the characters
"a" through "z" (lowercase). Some examples of legal names Web Programming
are Number_hits, temp99, and _name. Shahbaz Pervez
Literals
You use literals to represent values in JavaScript. These are fixed values, not
variables, that you literally provide in your script.

Integers

Floating-Point Literals
A floating-point literal can have the following parts:
•a decimal integer
•a decimal point (".")
•a fraction (another decimal number)
•an exponent
•a type suffix
The exponent part is an "e" or "E" followed by an integer, which can be signed
(preceded by "+" or "-"). A floating-point literal must have at least one digit and
either a decimal point or "e" (or "E"). E.g. 3.1415, -3.1E12, and 2E-12

Web Programming
Shahbaz Pervez
JavaScript special characters
Character Meaning

\b backspace

\f form feed

\n new line

\r carriage return

\t tab

\\ backslash character

Expressions and Operators


JavaScript has the following types of expressions:
•Arithmetic: evaluates to a number, for example 3.14159
•String: evaluates to a character string, for example, "Fred" or "234"
Logical: evaluates to true or false
Web Programming
Shahbaz Pervez
Operators
Assignment operators Comparison operators
Shorthand operator Meaning Operator Description Examples
returning
x += y x = x + y true1
Equal (==) Returns true if the operands are 3 == var1
x -= y x = x - y
equal.
x *= y x = x * y
Not equal Returns true if the operands are not var1 != 4
x /= y x = x / y (!=) equal.
x %= y x = x % y
Greater than Returns true if left operand is var2 >
x <<= y x = x << y (>) greater than right operand. var1

x >>= y x = x >> y Greater than Returns true if left operand is var2 >=
or equal (>=) greater than or equal to right var1
x >>>= y x = x >>> y operand. var1 >= 3
x &= y x = x & y Less than (<) Returns true if left operand is less var1 <
than right operand. var2
x ^= y x = x ^ y

x |= y x = x | y Less than or Returns true if left operand is less var1 <=


equal (<=) than or equal to right operand. var2
var2 <= 5

Web Programming
Shahbaz Pervez
Arithmetic Operators

+ - * /

Operat Description Example


or

% Binary operator. Returns the integer remainder of dividing the 2 operands. 12 % 5 returns 2.
(Modul
us)

++ Unary operator. Adds one to its operand. If used as a prefix operator (++x), If x is 3, then ++x sets x to 4 and returns
(Increm returns the value of its operand after adding one; if used as a postfix 4, whereas x++ sets x to 4 and returns 3.
ent) operator (x++), returns the value of its operand before adding one.

-- Unary operator. Subtracts one to its operand. The return value is analogous If x is 3, then --x sets x to 2 and returns
(Decre to that for the increment operator. 2, whereas x++ sets x to 2 and returns 3.
ment)

- Unary operator. Returns the negation of its operand. If x is 3, then -x returns -3.
(Unary
negatio
n)

Web Programming
Shahbaz Pervez
Logical operators

Operator Usage Description Example1

and expr1 && Returns expr1 if it converts to false. Otherwise, var1 && var2 returns
(&&) expr2 returns expr2. "Dog".
var2 && var3 returns
false

or (||) expr1 || Returns expr1 if it converts to true. Otherwise, var1 || var2 returns
expr2 returns expr2. "Cat".
var3 || var1 returns
"Cat". var3 || (3==4)
returns false.

not (!) !expr If expr is true, returns false; if expr is false, returns
true. !var1 returns false.
!var3 returns true.

1 Assume var1 is "Cat", var2 is "Dog", and var3 is false.

Web Programming
Shahbaz Pervez
Operator precedence
Operator type Individual operators

assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=

conditional ?:

logical-or ||

logical-and &&

bitwise-or |

bitwise-xor ^

bitwise-and &

equality == !=

relational < <= > >=

bitwise shift << >> >>>

addition/subtraction + -

multiply/divide * / %

negation/increment ! ~ - ++ --
Web Programming
call, member () [] . Shahbaz Pervez
Creating an Array
scores = new
Array(20);
Assigning Values:
scores[0] = 50;
scores[9] = 85;
OR
scores = new
Array(20,10,30,11,14);

var arlength = scores.length;


parseInt, parseFloat Functions
a = parseInt("39 steps"); //Returns 39

b = parseFloat(“12.94 steps"); //Returns 12.94

The eval Function


Web Programming
a = eval("20 + 1 + 4"); Shahbaz Pervez
Conditional Expression
condition ? Value1 : value2

var day = “saturday”


(day==“saturday”) ? “Its Weekend” : “Goto Work!”

Control Structures
For Loop While Loop
for(var I=0;I<=10;I++) var i=1;
{
document.writeln(i+”\n”) While(I<=10){
}
document.write(i+”\n”)
i++;
} Web Programming
Shahbaz Pervez
Dialog Boxes in JavaScript

Alert:
alert(“Hello World!”)

Confirm:
confirm(“Are you sure to Exit?”)

Prompt:

prompt(“Enter your name please”, “Name Here”)

A word on Conditional Checking in Java Script

if…else
switch…case Web Programming
Shahbaz Pervez
Defining and Calling Functions
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide script from old browsers
function square(number) {
return number * number;
}
// End script hiding from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT>
document.write("The function returned ",square(5));
</SCRIPT>
<P> All done.
</BODY>
Web Programming
Shahbaz Pervez
<HTML> <HEAD>
<TITLE>JavaScript table test</TITLE> Another Function
<SCRIPT language="JAVASCRIPT">
function PrintRow(name, age, birthday)
{
document.write("<TR> <TD>", name, "</TD> <TD>", age, "</TD>
<TD>", birthday, "</TD> </TR>\n");
}
</SCRIPT>
</HEAD>
<BODY>
<H1>Table Test Using JavaScript</H1>
<TABLE>
<SCRIPT language="JAVASCRIPT">
PrintRow("Fred", 27, "June 17");
PrintRow("Tom", 24, "March 13");
PrintRow("Rebecca", 25, "November 30");
</SCRIPT>
</TABLE>
End of table. Web Programming
</HTML> Shahbaz Pervez
Using String Objects-String Conversions
•toUpperCase() converts all characters in the string to uppercase.
•toLowerCase() converts all characters in the string to lowercase.
•substring(starting-index,end-index) Non-inclusive
•charAt(index-no)
alpha = "ABCDEFGHIJKLMNOPQRSTUVWMMMXYZ";
alpha.toLowerCase() //converts the text to lowercase
alpha.substring(0,4) returns "ABC".
alpha.substring(10,12) returns "KL".
alpha.charAt(0) returns "A".
alpha.charAt(12) returns "M".
location = alpha.indexOf(“GH"); //returns 6
location = alpha.indexOf(“M",19);
location = alpha.lastIndexOf(“M");

Web Programming
Shahbaz Pervez
Using String Objects-String Conversions

•String.big() displays big text


•String.blink() displays blinking text.
•String.bold() displays bold text
•String.fixed() displays fixed-font text
•String.fontcolor() displays the string in a colored font
•String.fontsize() changes the font size
•String.italics() displays the string in italics, using the <I> tag.
•String.small() displays the string in small letters
•String.strike() displays the string in a strike-through font
•String.sub() displays subscript text
•String.sup() displays superscript text

Web Programming
Shahbaz Pervez
Creating a Date Object
The following formats can be used:
birthday = new Date();
birthday = new Date("June 20, 1996 08:00:00");
birthday = new Date(6, 20, 96);
birthday = new Date(6, 20, 96, 8, 0, 0);
If you use no parameters, as in the first example, the current date is stored in the object.
You can then set the values using the set methods, described in the next section.
Setting Date Values
A variety of set methods enable you to set components of a Date object to values:
•setDate() sets the day of the month.
•setMonth() sets the month. JavaScript numbers the months from 0 to 11, starting with
January (0).
•setYear() sets the year.
•setTime() sets the time (and the date) by specifying the number of milliseconds since
January 1st, 1970.
•setHours(), setMinutes(), and setSeconds() set the time.
//e.g birth=new Date()
birth.setDate(23) Web Programming
document.write(birth) Shahbaz Pervez
Getting Date Values
You can use the get methods to get values from a Date object. This is the only way to obtain these
values, because they are not available as properties:
•getDate() gets the day of the month.
•getMonth() gets the month.
•getYear() gets the year.
•getTime() gets the time (and the date) as the number of milliseconds since January 1st, 1970.
•getHours(), getMinutes(), and getSeconds() get the time.
//e.g birth=new Date()
document.write(birth.getDate())

The Math Object


•Math.ceil() rounds a number up to the next integer.
•Math.floor() rounds a number down to the next integer.
•Math.round() rounds a number to the nearest integer.
Generating Random Numbers
Math.random()//generates a number b/w 0 & 1
//Function that generates a number b/w 1 and a value
function rand(num)
{ Web Programming
return Math.floor(Math.random() * num) + 1; } Shahbaz Pervez
Handling Events
Eve Applies to Occurs when Event
nt handler

Abort onAbort
images User aborts the loading of an image (for example by clicking a
link or clicking the Stop button)

Blur onBlur
windows and all form elements User removes input focus from window or form element

Chang onChange
text fields, textareas, select lists User changes value of element
e

Click onClick
buttons, radio buttons, checkboxes, submit User clicks form element or link
buttons, reset buttons, links

DragDr onDragDrop
windows User drops an object onto the browser window, such as
op
dropping a file on the browser window

Error onError
images, windows The loading of a document or image causes an error

Focus onFocus
windows and all form elements User gives input focus to window or form element

KeyDo onKeyDown
documents, images, links, text areas User depresses a key
wn

KeyPre onKeyPress
documents, images, links, text areas User presses or holds down a key
ss

Web Programming
Shahbaz Pervez
KeyUp onKeyUp
documents, images, links, text areas User releases a key

Load onLoad
document body User loads the page in the Navigator

MouseDown onMouseDown
documents, buttons, links User depresses a mouse button

MouseMove onMouseMove
nothing by default User moves the cursor

MouseOut onMouseOut
areas, links User moves cursor out of a client-side image map or link

MouseOver onMouseOver
links User moves cursor over a link

MouseUp onMouseUp
documents, buttons, links User releases a mouse button

Move onMove
windows User or script moves a window

Reset onReset
forms User resets a form (clicks a Reset button)

Resize onResize
windows User or script resizes a window

Select onSelect
text fields, textareas User selects form element's input field

Submit onSubmit
forms User submits a form

Unload onUnload
document body User exits the page

Web Programming
Shahbaz Pervez
Available events in JavaScript
Event Name Description
onAbort Occurs when the user aborts the loading of an image
onBlur Occurs when an object on the page loses focus
onChange Occurs when a text field is changed by the user
onClick Occurs when the user clicks on an item
onError Occurs when a document or image can't load correctly
onFocus Occurs when an item gains focus
onLoad Occurs when the page (or an image) finishes loading
onMouseOver Occurs when the mouse pointer moves over an item
onMouseOut Occurs when the mouse pointer moves off an item
onSelect Occurs when the user selects text in a text area
OnSubmit Occurs when a submit button is pressed
OnUnload Occurs when the user leaves the document or exits
Web Programming
Shahbaz Pervez
Web Programming
Shahbaz Pervez
Defining an Event Handler
<HEAD><SCRIPT>
<!--- Hide script from old browsers
function compute(f) {
if (confirm("Are you sure?"))
f.result.value = eval(f.expr.value)
else
alert("Please come back again.")
}
// end hiding from old browsers -->
</SCRIPT></HEAD>
<BODY><FORM>
Enter an expression:
<INPUT TYPE="text" NAME="expr" SIZE=15 >
<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)">
<BR>
Result:
<INPUT TYPE="text" NAME="result" SIZE=15 >
</FORM></BODY> Web Programming
Shahbaz Pervez
Calling Event Handlers Explicitly
In Navigator 3.0 and later releases, you can reset an event handler specified by
HTML, as shown in the following example.
<SCRIPT LANGUAGE="JavaScript">
function fun1() {
...
}
function fun2() {
...
}
</SCRIPT>
<FORM NAME="myForm">
<INPUT TYPE="button" NAME="myButton" onClick="fun1()">
</FORM>
<SCRIPT>
document.myForm.myButton.onclick=fun2 Web Programming
</SCRIPT> Shahbaz Pervez
<HEAD><SCRIPT> Another Event Handler
<!--- Hide script from old browsers
function compute(f) {
if (confirm("Are you sure?"))
f.result.value = eval(f.expr.value)
else
alert("Please come back again.")
}// end hiding from old browsers -->
</SCRIPT></HEAD>
<BODY><FORM>
Enter an expression:
<INPUT TYPE="text" NAME="expr" SIZE=15 >
<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)">
<BR>
Result:<INPUT TYPE="text" NAME="result" SIZE=15 ></FORM> Web Programming
Shahbaz Pervez
</BODY>
Object Hierarchy

Web Programming
Shahbaz Pervez
Every page has the following objects:
•navigator: has properties for the name and version of the Navigator
being used, for the MIME types supported by the client, and for the plug-ins
installed on the client.
•window: the top-level object; has properties that apply to the entire
window. There is also a window object for each "child window" in a frames
document.
•document: contains properties based on the content of the document,
such as title, background color, links, and forms.
•location: has properties based on the current URL.
•history: contains properties representing URLs the client has
previously requested.
To refer to specific properties, you must specify the object name and all its
ancestors. Generally, an object gets its name from the NAME attribute of the
corresponding HTML tag. For example, the following refers to the value
property of a text field named text1 in a form named myform in the current
document: document.myform.text1.value Web Programming Shahbaz Pervez
Document Properties: an Example
A document has a property for each form and each anchor in the document.
e.g.
<HEAD><SCRIPT>
function update(form) {
alert("Form being updated")
}
</SCRIPT></HEAD>
<BODY>
<FORM NAME="myform" ACTION="foo.cgi" METHOD="get" >
Enter a value:
<INPUT TYPE="text" NAME="text1" VALUE="blahblah" SIZE=20 >
Check if you want:
<INPUT TYPE="checkbox" NAME="Check1" CHECKED
onClick="update(this.form)"> Option #1
<P>
<INPUT TYPE="button" NAME="button1" VALUE="Press Me"
onClick="update(this.form)">
</FORM> Web Programming
</BODY> Shahbaz Pervez
Because there is a form in the document, there is also a Form object called
myform (based on the form's NAME attribute) that has child objects for the
checkbox and the button. Each of these objects has a name based on the NAME
attribute of the HTML tag that defines it, as follows:
•document.myform, the form
•document.myform.Check1, the checkbox
•document.myform.button1, the button

The Form object has child objects named button1 and text1, corresponding to
the button and text fields in the form. These objects have their own properties
based on their HTML attribute values, for example,
•button1.value is "Press Me"
•button1.name is "Button1"
•text1.value is "blahblah"
•text1.name is "text1"
In practice, you refer to these properties using their full names, for example,
document.myform.button1.value.
Web Programming
Shahbaz Pervez
Example object property values
Property Value

document.title "A Simple Document"

document.fgColor #000000

document.bgColor #ffffff

location.href "http://www.royalairways.com/samples/simple.html"

history.length 7

Web Programming
Shahbaz Pervez
Server-side Scripting
Server-side Scripting is a technology that allows for the programmatic construction of HTML
pages just before they are delivered to the browser.

Advantages of Server-side Scripting:


™ Allows you to run programs in programming languages that are not supported by your browser
™ Can provide the client data that do not reside on the client
™ Enables to write dynamic programs browser independently
™ Quicker loading time for dynamic web pages
™ Provides improved security.

Web-servers and ASP


™ MS Windows 2000 has its own web server – IIS 5.0
™ PWS(Personal web Server) can work with win 95 and 98.
™ PWS in Win NT was in fact IIS 4.0
™ Chili!Soft ASP (http:// www.chilisoft.com) enables you to run ASP on web servers from
Apache, Lotus, Netscape, O’Reily and Microsoft, running on Microsoft, Sun and IBM systems.
Chili!Soft 3.0 is latest final release.
™ Halcyon Software (http://www.halcyonsoft.com) provides a product called Instant ASP, which
runs as a Java Servelet on your web server to provide ASP support. Because it is a Java Servelet
you need JDK installed on your web server

Web Programming
Shahbaz Pervez
Web Server
‰Sends Client-side scripts to client for interpretation.
‰Converts server-side scripts into HTML and sends
back to client

test.asp

Request
(test.asp)
asp.dll
response

Script engine Script engine

Client (browser)
‰Browser interprets client-side scripts and HTML

Web Programming
Shahbaz Pervez
ASP Objects and Components
Object: Think of an object as a box containing set of functions and pieces of information
Components: A package of related objects.

ASP Objects

™ Request Object
™ Response Object
™ Session Object
™ Server Object
™ Application Object
™ ObjectContext Object
™ ASP Error Object

Alternatives to ASP

™ Cold Fusion
™ Personal Home Pages (PHP)
™ Java Server Pages (JSP)
™ Common Gateway Interface (CGI)
Web Programming
Shahbaz Pervez
Writing ASP Pages
<%
Response.write “Hello World”
%>

Capturing user information


info.html
<form action=“info.asp” method=“post”>
Enter your name:<input tyoe=“text” name=“username”>
<input type=“submit”>
</form>

info.asp
<%
Dim Urname
Urname=Request.form(“username”)
Response.write “Hello! “ & Urname
%>

Note: We can capture form data as below too


<%= username%>

Web Programming
Shahbaz Pervez
QueryString Collection

The QueryString collection retrieves form values passed to your Web


server as text following a question mark in the request URL. The
form values can be appended to the request URL by using either the
HTTP GET method or by manually adding the form values to the URL.
For example, if the previous form example used the GET method
(ACTION = "GET") and the user typed Jeff, Smith, and 30, then the
following URL request would be sent to the server:
http://scripts/Myfile.asp?firstname=Jeff&lastname=Smith&age=30&userstatus=ne
w
.
Myfile.asp might contain the following form processing script
Hello, <%= Request.QueryString("firstname") %>
<%= Request.QueryString("lastname") %>.
You are <%= Request.QueryString("age") %> years old
<%
If Request.QueryString("userstatus") = "new user" then

Response.Write"This is your first visit to this Web site!"


End if
%> Web Programming
Shahbaz Pervez
The QueryString collection also has an optional parameter that you
can use to access one of multiple values that appear in the request
body. You can also use the Count property to count the number of
times that a specific type of value appears.
For example, a form containing a list box with multiple items can
render the following request:
http://list.asp?food=apples&food=olives&food=bread
You could use the following command to count multiple values:
Request.QueryString("food").Count
To display the multiple values types, List.asp could contain the
following script:

<%Total = Request.QueryString("food").Count%>

<%For i = 1 to Total%>

<%= Request.QueryString("food")(i) %> <BR>

<%Next%>
The preceding script would display:
Apples
olives
bread Web Programming
Shahbaz Pervez
In this example, the script is in a file named Verify.asp, the same file
which contains the form. The form posts information to itself by
specifying Verify.asp in the ACTION attribute.

<% If Isnumeric(Request.QueryString("Age")) then %>

<p>Hello, your age is <%=Request.QueryString("age")%>

<%Else %>

<p>Please enter a numerical age.


<%End If %>

<FORM METHOD= "POST" ACTION="verify.asp" >


Name: <INPUT TYPE="text" NAME="Name" >
Age: <INPUT TYPE="text" NAME="Age" >
<INPUT TYPE="submit" VALUE="Enter">
</FORM> Web Programming
Shahbaz Pervez
Accessing a Database

You can create a file based DSN by opening Control Panel from the
Windows Start menu. Double-click the ODBC icon, and then select
the File DSN property sheet. Click Add, choose your database's
driver, and then click Next. Follow the proceeding instructions for
configuring a DSN for your particular database software.

To configure a Microsoft Access Database File DSN

In the Create New Data Source dialog box, select Microsoft Access
Driver from the list box, then click Next.

. Type in a name for your DSN file, then click Next. Web Programming
Shahbaz Pervez
o configure an Oracle Database File DSN

ake sure that the Oracle client software is correctly installed on the
computer where you intend to create the DSN. Consult your server
administrator and database software documentation for more
information.

1 On the Create New Data Source dialog box, select Microsoft


ODBC for Oracle from the list box, then click Next.

Type in a name for your DSN file, then click Next.

Click Finish to create the data source.

Enter a user name, password, and server name, then click OK.
Web Programming
Shahbaz Pervez
Connecting to a Database
To establish a database connection, you first create an instance of
the Connection object. For example, the following script
instantiates the Connection object and proceeds to open a
connection:
<%
'Create a connection object
Set cn = Server.CreateObject("ADODB.Connection")

'Open a connection; the string refers to the DSN

cn.Open "FILEDSN=MyDatabase.dsn"%>

Web Programming
Shahbaz Pervez
Executing Queries with the Connection Object
<%

'Define file based DSN

strDSN = "FILEDSN=MyDatabase.dsn"

'Instantiate the Connection object and open a database connection

Set cn = Server.CreateObject("ADODB.Connection")
cn.Open strDSN

'Define SQL SELECT statement


strSQL = "INSERT INTO Customers (FirstName, LastName) VALU
('Jose','Lugo')"
'Use the Execute method to issue a SQL query to database
cn.Execute(strSQL) %>

Web Programming
Shahbaz Pervez
Using the Recordset Object for Manipulating Results

Web Programming
Shahbaz Pervez

You might also like