Sie sind auf Seite 1von 92

Study Material

for

WEB TECHNOLOGIES

BCA
(2
ND
SEM)






Poonam Verma










Contents:

UNIT I
Web Essentials:
Clients, Servers and communication , HTTP request message-response message.Web Clients,
Web Servers-Case Study. Markup Languages, XHTML :An Introduction to XHTML, History-
Versions- Basic XHTML, Syntax and Semantics, Introduction to Dynamic web designing and
Scripting Languages, Client Side and Server Side Scripting

UNIT II
JavaScript:
Introduction to JavaScript, Elements of JavaScript, Variables, DataTypes,Operators,Control
Statements , Functions , Dialogs: performing I/O, Objects in JavaScript, Document Object
Model, Form Controls and Event Handling.

UNIT III
ASP:
Introduction to ASP, ASP first Script, Programming features of ASP- Operators, Variables, if
statement, select statement, static and dynamic arrays, ASP procedures, Do Loop, for Loop,
Subroutines and strings, ASP forms-forms with get and post method.


UNIT IV
ASP with ADO:
Accessing a database from an asp page, ADO-active x data objects, ADO database connection,
display records, add records, sort records, delete records, update records from an ASP page
through ADO.


UNIT V
XML:
Features of XML, XML Mark up : Element markup, Attribute Markup, Element declarations,
element content models: Element Sequences , Element choices, Combined sequences and
choices, Element Occurrence Indicators: Discussion of three occurrence indicators ?(Question
Mark) *(Asterisk Sign) + ( plus Sign), Character Content, PCDATA , Document Type
Declaration and Validation, Developing a DTD from XML Code.









Unit I
Web Essentials

Learning Objectives:

After studying this unit, you should be able to :
Describe Web technology
Describe the Web Essentials of the Internet
Define the communication with the help of HTTP
Understand the markup Languages
Define XHTML
Describe the different features and versions of XHTML

1.1 Introduction:

Internet is a network of networks that consists of millions of private, public, academic,
business, and government networks, of local to global scope, that are linked by a broad array of
electronic, wireless, and optical networking technologies.

Web technologies related to the interface between web servers and their clients. This
information includes markup languages, and standards for document identification and display.
It can reach many people all over the world on multiple platforms and operating systems to
make the Internet more powerful and easier to use.


1.2 Web Essentials: Clients, servers and Communication.


A client computer and a server computer are usually two separate devices, each customized for
their designed purpose. For example, a Web client works best with a large screen display, while
a Web server does not need any display at all and can be located anywhere in the world.
However, in some cases a given device can function both as a client and a server for the same
application. Likewise, a device that is a server for one application can simultaneously act as a
client to other servers, for different applications.

Client-server is just one approach to managing network applications The primary alternative,
peer-to-peer networking, models all devices as having equivalent capability rather than
specialized client or server roles. Compared to client-server, peer to peer networks offer some
advantages such as more flexibility in growing the system to handle large number of clients.
Client-server networks generally offer advantages in keeping data secure.




Clients:

Client devices are typically PCs with network software applications installed that request and
receive information over the network. Mobile devices as well as desktop computers can both
function as clients.

Servers:

A server device typically stores files and databases including more complex applications like
Web sites. Server devices often feature higher-powered central processors, more memory, and
larger disk drives than clients.


Process of Communication:

Clients and servers exchange messages in a request-response messaging pattern: The client sends
a request, and the server returns a response. This exchange of messages is an example of inter-
process communication. To communicate, the computers must have a common language, and
they must follow rules so that both the client and the server know what to expect. The language
and rules of communication are defined in a communications protocol. All client-server
protocols operate in the application layer.
A server may receive requests from many different clients in a very short period of time.
Because the computer can perform a limited number of tasks at any moment, it relies on
a scheduling system to prioritize incoming requests from clients in order to accommodate them
all in turn.

Example :
When a bank customer accesses online banking services with a web browser (the client), she
initiates a request to the bank's web server. Since the customer's login credentials are stored in
a database, the web server runs a program to access a database server. This database server may,
in turn, fetch financial transaction records from another database server.
An application server interprets the returned data by following the bank's business logic, and
provides the output to the web server. Finally, the web server sends the result to the web
browser, which interprets the data.
Each server listed above acts as a client when it submits data in a request to another server for
processing. In each step of this sequence of clientserver message exchanges, a computer
processes a request and returns data. This is the request-response messaging pattern. When all
the requests are met, the sequence is complete and the web browser presents the data to the
customer.



The principle of communication between a client and a server is composed of successions of
requests and responses.
The principle of communication is as explain below:
A Web client (or browser) sends requests to a Web server. Every retrievable piece of
information on the Web is identified by a Uniform Resource Locator (URL), which
includes the name of the object, where it is located, and the protocol used to get it.
The Web server is responsible for document storage and retrieval. It sends the document
requested (or an error message) back to the requesting client.
The Browser interprets and presents the document. The browser is responsible for
document presentation.
1.2 a)Communication through HTTP
The Full Form of HTTP is HyperText Transfer Protocol .
The language that Web clients and servers use to communicate with each other is called the
Hypertext Transfer Protocol (HTTP). All Web clients and servers must be able to speak
HTTP in order to send and receive hypermedia documents.
HTTP is the set of rules for transferring files (text, graphic images, sound, video, and other
multimedia files) on the World Wide Web. As soon as a Web user opens their Web browser,
the user is indirectly making use of HTTP. HTTP is an application protocol that runs on top of
the TCP/IP suite of protocols (the foundation protocols for the Internet).


HTTP concepts include (as the Hypertext part of the name implies) the idea that files can
contain references to other files whose selection will elicit additional transfer requests. Any
Web server machine contains, in addition to the Web page files it can serve and an HTTP
daemon, a program that is designed to wait for HTTP requests and handle them when they
arrive.
Web browser on our computer is an HTTP client, sending requests to server machines. When
the browser user enters file requests by either "opening" a Web file or clicking on a hypertext
link, the browser builds an HTTP request and sends it to the Internet Protocol address (IP
address) indicated by the URL.
The HTTP daemon in the destination server machine receives the request and sends back the
requested file or files associated with the request. (A Web page often consists of more than
one file.)








1.3 Mark up Languages

History of MarkUp Languages:
A (document) markup language is a modern system for annotating a document in a way that
is syntactically distinguishable from the text. The idea and terminology evolved from the
"marking up" of paper manuscripts, i.e., the revision instructions by editors, traditionally written
with a blue pencil on authors' manuscripts.
In digital media this "blue pencil instruction text" was replaced by tags, that is, instructions are
expressed directly by tags or "instruction text encapsulated by tags".
In 1989, physicist Sir Tim Berners-Lee wrote a memo proposing an Internet-
based hypertext system, then specified HTML and wrote the browser and server software in the
last part of 1990.
The first publicly available description of HTML was a document called "HTML Tags", first
mentioned on the Internet by Berners-Lee in late 1991. It describes 18 elements comprising the
initial, relatively simple design of HTML. Except for the hyperlink tag, these were strongly
influenced by SGMLguid, an in-houseSGML-based documentation format at CERN. Eleven of
these elements still exist in HTML 4.
Berners-Lee considered HTML to be an application of SGML. It was formally defined as such
by the Internet Engineering Task Force (IETF) with the mid-1993 publication of the first
proposal for an HTML specification: "Hypertext Markup Language (HTML)" Internet-Draft by
Berners-Lee and Dan Connolly, which included an SGML Document Type Definition to define
the grammar.
Many of the HTML text elements are found in the 1988 ISO technical report TR
9537 Techniques for using SGML, which in turn covers the features of early text formatting
languages such as that used by the RUNOFF command developed in the early 1960s for
the CTSS (Compatible Time-Sharing System) operating system. These formatting commands
were derived from those used by typesetters to manually format documents.
Steven DeRose argues that HTML's use of descriptive markup (and influence of SGML in
particular) was a major factor in the success of the Web, because of the flexibility and
extensibility that it enabled. HTML became the main markup language for creating web pages
and other information that can be displayed in a web browser, and is quite likely the most used
markup language in the world today.







1.4 XHTML
Introduction to XHTML
XHTML (Extensible HyperText Markup Language) is a family of XML markup languages that
mirror or extend versions of the widely used Hypertext Markup Language (HTML), the language
in which web pages are written.
While HTML (prior to HTML5) was defined as an application of Standard Generalized Markup
Language (SGML), a very flexible markup language framework, XHTML is an application
of XML, a more restrictive subset of SGML. Because XHTML documents need to be well-
formed, they can be parsed using standard XML parsersunlike HTML
XHTML was developed to make HTML more extensible and increase interoperability with other
data formats. HTML 4 was ostensibly an application of Standard Generalized Markup
Language (SGML); however the specification for SGML was complex, and neither web
browsers nor the HTML 4 Recommendation were fully conformant to it.
.

The XML standard, approved in 1998, provided a simpler data format closer in simplicity to
HTML 4. By shifting to an XML format, it was hoped HTML would become compatible with
common XML tools; servers and proxies would be able to transform content, as necessary, for
constrained devices such as mobile phones. By using namespaces, XHTML documents could
provide extensibility by including fragments from other XML-based languages such as Scalable
Vector Graphics .

Versions of XHTML:
XHTML 1.0
December 1998 saw the publication of a W3C Working Draft entitledReformulating HTML in
XML. This introduced Voyager, the codename for a new markup language based on HTML 4,
but adhering to the stricter syntax rules of XML. By February 1999 the name of the specification
had changed to XHTML 1.0: The Extensible HyperText Markup Language, and in January 2000
it was officially adopted as a W3C Recommendation.
There are three formal DTDs for XHTML 1.0, corresponding to the three different versions of
HTML 4.01:
XHTML 1.0 Strict is the XML equivalent to strict HTML 4.01, and includes elements and
attributes that have not been marked deprecated in the HTML 4.01 specification. As of May
25, 2011, XHTML 1.0 Strict is the document type used for the homepage of the website of
the World Wide Web Consortium.
XHTML 1.0 Transitional is the XML equivalent of HTML 4.01 Transitional, and includes
the presentational elements (such ascenter, font and strike) excluded from the strict version.
XHTML 1.0 Frameset is the XML equivalent of HTML 4.01 Frameset, and allows for the
definition of frameset documentsa common Web feature in the late 1990s.


XHTML Syntax:
XHTML is a markup language that specifies the format of text that is displayed in a Web browser, such as
Microsofts Internet Explorer or Netscapes Com-municator. One key issue when using XHTML is
the separation of the presentation of a document . (i.e., the documents appearance when rendered
by a browser) from the structure of the documents information.
XHTML markup contains text that represents the content of a document and elements that specify a
documents structure. Some important elements of an XHTML document include the html element, the
head element and the body element. The html element encloses the head section (represented by the head
element) and the body section (represented by the body element). The head section contains information
about the XHTML document, such as the title of the document. The head section also can contain
special document-formatting instructions called style sheets and client-side programs called scripts for
creating dynamic Web pages. The body section contains the pages content that the browser displays
when the user visits the Web page.
XHTML documents delimit an element with start and end tags. A start tag consists of the element name
in angle brackets (e.g., <html> ). An end tag consists of the element name preceded by a / in angle
brackets (e.g., </html> )
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3` "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. E.1: main.html -->
6 <!-- Our first Web page. -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Our first Web page</title>
11 </head>
12
13 <body>
14 <p>Welcome to XHTML!</p>
15 </body>
16 </html>


Explanation:
Lines 13 are required in XHTML documents to conform with proper XHTML syntax.
Lines 56 are XHTML comments. XHTML document creators insert comments to improve
markup readability and to describe the content of a document. Comments also help other people
read and understand an XHTML documents markup and content. Comments do not cause the
browser to perform any action when the user loads the XHTML document into the Web browser
to view the document.
In this example, lines 8 and 16 define the start and end of the html element. Note that the end tag
on line 16 has the same name as the start tag, but is preceded by a / inside the angle brackets.
Many start tags define attributes that provide additional information about an element. Browsers
can use this additional information to determine how to process the element.
Lines 911 define the Web pages head section with a head element. Line 10 specifies a title
element. This is called a nested element, because it is enclosed in the head elements start and
end tags. The head element also is a nested element, because it is enclosed in the html elements
start and end tags. The title element describes the Web page.
Line 13 opens the documents body element. The body section of an XHTML document
specifies the documents content, which may include text and tags. Some tags, such as the
paragraph tags (<p> and </p> ) in line 14, mark up text for display in a browser. All text placed
between the <p> and </p> tags form one paragraph. When the browser renders a paragraph, a
blank line usually precedes and follows paragraph text.
This document ends with two closing tags (lines 1516). These tags close the body and html
elements, respectively. The ending </html> tag in an XHTML document informs the browser
that the XHTML markup is complete.












1.5 Dynamic Web Designing
A server-side dynamic web page is a web page whose construction is controlled by
an application server processing server-side scripts. In server-side scripting parameters determine
how the assembly of every new web page proceeds, including the setting up of more client-side
processing.
A client-side dynamic web page processes the web page using HTML scripting running in the
browser as it loads. JavaScript and other scripting languages determine the way the HTML in the
received page is parsed into the Document Object Model, or DOM, that represents the loaded
web page. The same client-side techniques can then dynamically update or change the DOM in
the same way.
A dynamic web page is then reloaded by the user or by a computer program to change some
variable content. The updating information could come from the server, or from changes made to
that page's DOM. This may or may not truncate the browsing history or create a saved version to
go back to, but a dynamic web page update using Ajax technologies will neither create a page to
go back to, nor truncate the web browsing history forward of the displayed page. Using Ajax
technologies the end user gets one dynamic page managed as a single page in the web
browser while the actual web content rendered on that page can vary. The Ajax engine sits only
on the browser requesting parts of its DOM, the DOM, for its client, from an application server.


1.6 Server-side scripting


A program running on a web server (server-side scripting) is used to generate the web content on
various web pages, manage user sessions, and control workflow. Server responses may be
determined by such conditions as data in a posted HTML form, parameters in the URL, the type
of browser being used, the passage of time, or a database or server state.
Such web pages are often created with the help of server-side languages such
as ASP,ColdFusion, JavaScript Perl, PHP, Ruby, WebDNA and other languages. These server-
side languages often use the Common Gateway Interface (CGI) to produce dynamic web pages.
Two notable exceptions are ASP.NET, and JSP, which reuse CGI concepts in their APIs but
actually dispatch all web requests into a shared virtual machine.
Dynamic web pages are often cached when there are few or no changes expected and the page is
anticipated to receive considerable amount of web traffic that would create slow load times for
the server if it had to generate the pages on the fly for each request.


1.7 Client-side scripting
Client-side scripting is changing interface behaviors within a specific web page in response to
mouse or keyboard actions, or at specified timing events. In this case, the dynamic behavior
occurs within the presentation. The Client-side content is generated on the user's local computer
system.
Such web pages use presentation technology called rich interfaced pages. Client-side scripting
languages like JavaScript or ActionScript, used for Dynamic HTML (DHTML)
and Flash technologies respectively, are frequently used to orchestrate media types (sound,
animations, changing text, etc.) of the presentation. The scripting also allows use of remote
scripting, a technique by which the DHTML page requests additional information from a server,
using a hidden frame, XML HttpRequests, or a Web service
The first "widespread used" version of JavaScript was in 1996 (with Netscape
3 and ECMAScript standard).
Example
The Client-side content is generated on the client's computer. The web browser retrieves a page
from the server, then processes the code embedded in the page (typically written in JavaScript)
and displays the retrieved page's content to the user.
The innerHTML property (or write command) can illustrate the "Client-side dynamic page"
generation: two distinct pages, A and B, can be regenerated (by an "event response dynamic")
as document.innerHTML = A and document.innerHTML = B; or "on load dynamic"
by document.write(A) and document.write(B).



Unit II
JAVASCRIPT
Learning Objectives:

After studying this unit, you should be able to :
Describe Javascript
Describe features of JavaScript
Define the Variables and their data types used in JavaScript
Define Control Statements
Describe Functions
Describe the JavaScript Objects
Understand the concept of Document and Event Handling
Write programs of Javascript with form controls

2.1 Introduction

JavaScript (JS) is a dynamic interpreted computer programming language. It is most commonly
used as part of web browsers, whose implementations allow client-side scripts to interact with
the user, control the browser, communicate asynchronously, and alter the document content that
is displayed. It is also being used in server-side programming, game development and the
creation of desktop and mobile applications. It supports many advanced concepts such as object-
oriented-programing , recursion, lambda, and closures and is an approachable language for
beginners.


For Javascript all that is required is a simple text-editor and a browser. In windows, one can use
notepad under the accessories and Linux and mac users have a similar editor.

2.2 Features of Javascript are :

i. Javascript is case sensitive
ii. Javascript is an event driven language which means the scripts written react to events
that are set up.
iii. Javascript is not a strongly typed language which means one need not be concern with the
type of data a variable is storing, only what the variable is storing and in Javascript,
variables can store anything, even functions.
iv. Variables in Javascript have FUNCTION scope. That is, all variables are global unless
they are explicitly defined inside a function and even then child-functions have access to
their parent's variables. If a function defines a new variable WITHOUT using the var
keyword, that variable will be global in scope.
v. Javascript supports true and false as boolean values.
vi. JavaScript is almost entirely object-based. Object property names are string keys. They
support two equivalent syntaxes: dot notation (obj.x = 10) and bracket notation
(obj['x'] = 10). Properties and their values can be added, changed, or deleted at run-time.
Most properties of an object (and those on its prototype inheritance chain) can be
enumerated using a for...in loop. JavaScript has a small number of built-in objects such
as Function and Date.
vii. JavaScript also supports regular expressions in a manner similar to Perl, which provide a
concise and powerful syntax for text manipulation that is more sophisticated than the
built-in string functions



2.3 Variables: Storing Data for your Program

Its possible to write a program that defines the value of every single piece of data it uses, but
thats like driving a ski liftone does not get to choose where theyre going. If one wants the
program to be able to take user input, and adapt to different pages and situations, one has to have
some way of working with values that one does not know in advance.
If we want the program to be a bit more flexible, we need to abstract some of its components.
And one of those methods are the use of variables.

Variables allow us to give a piece of data a name, then reference that data by its name further
along in our program. This way, we can reuse a piece of data without having to remember what
its actual value was; all we have to do is remember a variable name.
In JavaScript, we create a variable by using the keyword var and specifying the name we want to
use:

var chameleon;

This is called declaring a variable.
Having been declared, chameleon is ready to have some data assigned to it. This can be done
with the help of the assignment operator (=), placing the variable name on the left and the data
on the right:
var chameleon;
chameleon = "blue";
This whole process can be shortened by declaring and assigning the variable in one go:
var chameleon = "blue";


variable names can comprise almost any combination of letters and numbers, though no spaces
are allowed. Most punctuation and symbols have special meaning inside JavaScript, so the dollar
sign ($) and the underscore (_) are the only non-alphanumeric characters allowed in variable
names. Variable names are also case-sensitive, so the names chameleon, Chameleon, and
CHAMELEON refer to unique variables that could exist simultaneously.


these are all acceptable variable declarations:
var chameleon = "blue";
var Chameleon = "red";
var CHAMELEON = "green";
var yellow_chameleon = "yellow";
var orangeChameleon = "orange";
var chameleon$ = "greedy";

Its standard practice to create variable names in lowercase letters, unless youre concatenating
more than one word. And as I mentioned, variable names cant have spaces in them, so if you
want a variable name to include more than one word, you can separate each word with an
underscore (multi_word_variable) or capitalize the first letter of each word except for the first
(multiWordVariable)

Logical and Comparison Operators to be used with variables

Javascript supports equality checking (==) and identity checking (===). Equality checks for
equality regardless of type. Therefore 25 and '25' will evaluate as true. Identity checking checks
not only for equality but type equality as well so 25 and '25' will evaluate as false because, while
both are 25, one is a string and the other a number.
Note that a single equal sign is an assignment statement! x=5 will assign 5 to x, while x==5 will
see if x is equal to 5, and x===5 will check to see if x is identical to 5.
In addition to == and ===, you can check for not equal (!=) and not identical (!==).
Operator Description
= Assignment x=5; // assigns 5 to x
== Equality, is x==5?
=== Identity, is x 5 and a number as well?
!= Not equal, is x unequal to 5?
!== Not identical, is x unequal to the Number 5?
|| OR, is (x==5) OR (y==5)
&& And, is (x==5) AND (y==5)
< Less than. is x less than 5?
<= Less than or equal. is x less than or equal to 5?
> Greater than. is x greater than 5?
>= Greater than or qual. is x greater than or equal to 5?
2.4 Variable Types: Different Types for Different Data


JavaScript, however, is loosely typedthe language doesnt care what the variables hold. A
variable could start off holding a number, then change to holding a character, a word, or anything
else one wants it to hold.

In JavaScript, we can work with numbers, strings, Booleans, arrays and objects.


(a) Numbers

Numbers in JavaScript come in two ways: whole numbers and decimals. The technical term for a
whole number is an integer or int. A decimal is called a floating point number, or float. These
terms are used in most programming languages, including JavaScript.
To create a variable with numerical data, you just assign a number to a variable name:
var whole = 3;var decimal = 3.14159265;
Floating point numbers can have a practically unlimited number of decimal places:
var shortDecimal = 3.1;
var longDecimal = 3.14159265358979323846264338327950288419716939937;



(b) Strings

A string is a series of characters of any length, from zero to infinity . Those characters could be
letters, numbers, symbols, punctuation marks, or spaces.To specify a string, we surround a series
of characters with quote marks.
Its okay to include a single quote inside a double-quoted string, or a double quote inside a
single-quoted string, but if we require to include a quote mark inside a string thats quoted with
the same mark, you must precede the internal quote marks with a backslash (\). This is called
escaping the quote marks:
var singleEscape = 'He said \'RUN\' ever so softly.';
var doubleEscape = "She said \"hide\" in a loud voice.";
Those backslashes disappear when the string is actually used.



(c) Booleans

Boolean values are fairly simple, reallythey can be either true or false.
Theyre used mainly when were making decisions. In order to assign a Boolean value to a
variable, simply specify which state should be given to it. true and false are keywords in
JavaScript, so no need to put any quote marks around them:
var lying = true;
var truthful = false;


(d) Arrays


Numbers, strings and Booleans are good ways to store individual pieces of data, but what
happens when a group of data values are required to be work upon, like a list of names or a series
of numbers? One could create a whole bunch of variables, which would be a tough job to
manage.

Arrays solve this problem by providing , an ordered structure for storing a group of values.
Array can be thought of as being like a rack in which each slot is able to hold a distinct value.
In order to create an array, we use the special array markers, which are the opening and closing
square brackets:
var rack = [];
The variable rack is now an array, but theres nothing stored in it.
Each slot in an array is actually called an element, and in order to put some data into an
element ,it has to be correctly referenced which element is required to be put in. This reference
is called an index, which is a number that represents an elements position in an array. The first
element in an array has an index of 0. The second element has an index of 1, the third: 2, and so
on.
To reference a particular element, we use the variable name, followed by an opening square
bracket, then the index and a closing square bracket, like this:

var rack = [];
rack[0] = "First";
rack[1] = "Second";

An array storing data sequentially, starting index at 0.

Its possible to populate an array when its declared. We simply insert values, separated with
commas, between the square brackets:
var rack = ["First", "Second", "Third", "Fourth"];
That statement says that we should create an arrayrackthat has four elements with the values
specified here. The first value will have an index of 0, the second value an index of 1, and so on.

Arrays can contain any data typenot just stringsso you could have an array of numbers:
var numberArray = [1, 2, 3, 5, 8, 13, 21, 34];
An array of strings:
var stringArray = ["Veni", "Vidi", "Vici"];
A mixed array, containing multiple data types, would look like this:
var mixedArray = [235, "Parramatta", "Road"];
Heres an array of arrays:
var subArray1 = ["Paris", "Lyon", "Nice"];
var subArray2 = ["Amsterdam", "Eindhoven", "Utrecht"];
var subArray3 = ["Madrid", "Barcelona", "Seville"];
var superArray = [subArray1, subArray2, subArray3];

That last example is a multi-dimensional array.





2.5 Conditions and Loops: Controlling Program Flow

The way we make those decisions is through the use of special structures called conditions and
loops, which help to control which parts of your program will run under particular conditions,
and how many times those parts will be run.

Although a program might seem like a linear pathone statement following another
conditional statements act like intersections, allowing to change directions on the basis of a
given condition.

(a) if Statements
The most common conditional statement is an if statement. An if statement checks a
condition, and if that condition is met, allows the program to execute some code. If the
condition isnt met, the code is skipped.
The flow of a program through an if statement can be visualized as in Figure:


Syntax for if statements:
if (condition)
{
conditional code;
}
Instead of a semicolon, an if statement ends with the conditional code between curly
braces ({}).


The condition has to be contained within round brackets (also called parentheses) and
will be evaluated as a Boolean, with true meaning the code between the curly braces will
be executed and false indicating it will be skipped.


(b) if-else Statements
An if statement allows to execute some code when a condition is met, but doesnt offer
any alternative code for cases when the condition isnt met.
In an if-else statement, after the closing brace of the if, an else is included, which
specifies code to be executed when the condition of the if statement fails:

Syntax of if else statement:
if (condition){
conditional code;}else{
alternative conditional code;}
Example:
var name = "Marcus";
if (name == "Maximus")
{
alert("Good afternoon, General.");
}

else
{
alert("You are not allowed in.");
}




(c) else-if Statements:

If you want to provide some alternative code for cases in which an if statement fails, but
you want to further assess the data in order to decide what course of action to take, an
else-if statement is what you need. Instead of just typing else, type else if, followed by
the extra condition you want to test:
var name = "Marcus";
if (name == "Maximus")
{
alert("Good afternoon, General.");
}
else if (name == "Marcus")
{
alert("Good afternoon, Emperor.");
}
else
{
alert("You are not allowed in.");
}
You can chain together as many else-if statements as you want, and at the end, you can
include a normal else statement for use when everything fails.



(d) while Loops
while is the simplest of the loops. All it needs is a condition, and some conditional code:


while (condition){
conditional code;}
When the program first encounters the while loop, it checks the condition. If the
condition evaluates to true, the conditional code will be executed. When the program
reaches the end of the conditional code, it goes back up to the condition, checks it, and if
it evaluates to true, the conditional code will be executed and so on,
A while loop only finishes when its condition evaluates to false. This means its
important to have something inside the conditional code that will affect the condition,
eventually making it evaluate to false. Otherwise, your program will never escape the
while loop, and will repeat the conditional code forever, causing the browser to become
unresponsive.


Loops are extremely handy when theyre used in conjunction with arrays, because they
allow you to step sequentially through the array and perform the same operation on each
element.

To step through an array with a while loop an incrementing counter is required that starts
at 0 and increases by one each time the loop executes. This incrementor will keep track of
the index of the element that were currently working with. When we reach the end of the
array, we need to make it stopthats where we use the arrays length property.


In this example, well multiply each element of the numbers array by two:
var numbers = [1, 2, 3, 4, 5];
var incrementer = 0;
while (incrementer < numbers.length)
{
numbers[incrementer] *= 2;
incrementer++;
}



The conditional code inside that while loop uses incrementer as the index for the array. Starting
at 0, this variable will reference the first element, but because we increase it by one for each
execution of the loop, it will step through all of the elements in turn. Once incrementer has the
same value as numbers.length, the condition will fail and the program will exit the while loop,
having doubled all the elements in the array.


(e) do-while Loops
A do-while loop behaves almost identically to a while loop, with one key difference: the
conditional code is placed before the condition, so the conditional code is always
executed at least once, even if the condition is immediately false.

The conditional code is placed inside the curly braces of the do; the whilestatement
contains the condition right after that:
do{
conditional code;}
while (condition);



eg:
var numbers = [1, 2, 3, 4, 5];
var i = 0;
while (i < numbers.length)
{
numbers[i] *= 2;
i++;
}




(f) for Loops
for Loops are like while loops, but they offer a couple of handy shortcuts for statements
that we commonly use with loops.



var numbers = [1, 2, 3, 4, 5];
for (var i = 0; i < numbers.length; i++)
{
numbers[i] *= 2;
}
A for loop shortens two aspects of the while loop: the declaration of a counter variable,
and the incrementing of that variable.
The first statement is the declaration. It allows us to declare a counter variablein this
case iand set its initial value.
The second statement is the condition that controls the loop. Just like the condition in a
while loop, this condition must evaluate to true in order for the conditional code to be
executed. Its evaluated as soon as the program reaches the forloop (but after the counter
has been declared), so if it evaluates to false immediately, the conditional code will never
be executed.
The third statement is an action that will be executed every time the program reaches the
end of the conditional code. It is normally used to increment (or decrement) the counter,
but you could theoretically put anything in there.


2.6 Functions


Functions are like little packages of JavaScript code waiting to be called into action.
We have used the alert function to pop up an alert box in the browser. alert is a function thats
native to all browsersthat means it comes built-in with the browsers JavaScript interpreter
but its possible to create your own functions, which you can call whenever you want.
A function can essentially be seen as a wrapper for a block of code. All you need to do is name
that block, and youll be able to call it from other areas of your program, whenever you like.
You can define your own functions using the function keyword. This tells the program that
youre defining a new function, and that the code contained between the curly braces that follow
should be executed whenever that function is called:


function warning()
{
alert("This is your final warning");
}

The name that follows the function keyword is the name that you want to give your function
(function names have the same restrictions as variable names). This is the name youll call
whenever you want your program to run the code inside the function. The name must be
followed by round bracketstheyre empty in this instance.
In the example above, we created a new function called warning, so whenever we make a call to
this function, the statements inside the function will be executed, causing an alert box to appear,
displaying the text, This is your final warning.
As in the function declaration above, round brackets must appear immediately after the function
name in a function call:
warning();
These brackets serve two purposes: they tell the program that you want to execute the function,
and they contain the dataalso known as arguments.


Arguments: Passing Data to a Function

Functions can be designed to take as many arguments as you want, and those arguments dont
have to be stringsthey can be any sort of data that you can create in JavaScript.


When you define your function, you can provide names for the arguments that are to be passed to
it. These are included in the round brackets immediately after the function name, with a comma
separating arguments in cases where theres more than one:
function sandwich(bread, meat)
{
alert(bread + meat + bread);
}
Once an argument name has been defined in the function declaration, that argument becomes a
variable thats available every time the function is run, allowing you to use the data passed to the
function inside the function itself.
As you can see in the sandwich function above, two arguments are defined: bread and meat.
These two arguments are used in a call to alert and produce a little nonsensical message to the
user.


Return Statements: Outputting Data from a Function

A function may return data to the statement that called it. The neat thing about that is that you
can assign a function call as the value of a variable, and that variables value will become
whatever was returned by the function.
To get a function to return a value, we use the return keyword, followed by the value we want it
to return:

function sandwich(bread, meat)
{
var assembled = bread + meat + bread;
return assembled;
}


A return statement is always the final act of a function; nothing else is processed after a function
has returned. Consider this code:
function prematureReturner()
{
return "Too quick";
alert("Was it good for you?");
}

The alert function wouldnt be called, because the return statement would always cut off
execution of the function. This ability to cut off execution of a function with a return statement
can be handy when used in conjunction with a conditional statement, where you only want the
rest of the function to be executed if a certain condition is met.



2.7 Objects
________________________

Objects are really just amorphous programming blobs. Theyre an amalgam of all the other data
types, existing mainly to make life easier for programmers. Still, their vagueness of character
doesnt mean theyre not useful.
Objects exist as a way of organizing variables and functions into logical groups. Objects do this
by grouping together sets of properties and methods. Properties are variables that are only
accessible via their object, and methods are functions that are only accessible via their object. By
requiring all access to properties and methods to go through the objects that contain them,
JavaScript objects make it much easier to manage your programs.
when you create a new array, youre creating a new instance of the built-in Array object. The
length of an array is actually a property of that object, and arrays also have methods like pushv
and splice,
An array is a native object, because its built in to the JavaScript language, but its easy to create
your own objects using the Object constructor:

var Robot = new Object();

Once youve instantiated your new object, youre then free to add properties and methods to it, to
modify the values of existing properties, and to call the objects methods. The properties and
methods of an object are both accessed using the dot (.) syntax:
Robot.metal = "Titanium";
Robot.killAllHumans = function()
{
alert("Exterminate!");
};
Robot.killAllHumans();





(a) Date Object:
The Date object is used to work with dates and times.
Create a Date Object
The Date object is used to work with dates and times.
Date objects are created with the Date() constructor.
There are four ways of initiating a date:

new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Some examples of initiating a date:
var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)


(b) Math Object
The Math object allows you to perform mathematical tasks.
Math is not a constructor. All properties/methods of Math can be called by using Math as
an object, without creating it.

Syntax
var x = Math.PI; // Returns PI
var y = Math.sqrt(16); // Returns the square root of 16
Math Object Properties
Property Description
E Returns Euler's number (approx. 2.718)
LN2 Returns the natural logarithm of 2 (approx. 0.693)
LN10 Returns the natural logarithm of 10 (approx. 2.302)
LOG2E Returns the base-2 logarithm of E (approx. 1.442)









Math Object Methods
Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between -PI/2
and PI/2 radians
atan2(y,x) Returns the arctangent of the quotient of its arguments
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of E
x

floor(x) Returns x, rounded downwards to the nearest integer
LOG10E Returns the base-10 logarithm of E (approx. 0.434)
PI Returns PI (approx. 3.14)
SQRT1_2 Returns the square root of 1/2 (approx. 0.707)
SQRT2 Returns the square root of 2 (approx. 1.414)
log(x) Returns the natural logarithm (base E) of x
max(x,y,z,...,n) Returns the number with the highest value
min(x,y,z,...,n) Returns the number with the lowest value
pow(x,y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle


(c) String Object
The String object is used to manipulate a stored piece of text.
String objects are created with new String().

Syntax
var txt = new String("string");
or
var txt = "string";
String Object Methods
Method Description
charAt() Returns the character at the specified index
charCodeAt() Returns the Unicode of the character at the specified index
concat() Joins two or more strings, and returns a copy of the joined strings
fromCharCode() Converts Unicode values to characters
indexOf() Returns the position of the first found occurrence of a specified
value in a string
lastIndexOf() Returns the position of the last found occurrence of a specified
value in a string
localeCompare() Compares two strings in the current locale
match() Searches for a match between a regular expression and a string,
and returns the matches
replace() Searches for a match between a substring (or regular expression)
and a string, and replaces the matched substring with a new
substring
search() Searches for a match between a regular expression and a string,
and returns the position of the match
slice() Extracts a part of a string and returns a new string
split() Splits a string into an array of substrings
substr() Extracts the characters from a string, beginning at a specified
start position, and through the specified number of character
substring() Extracts the characters from a string, between two specified
indices
toLocaleLowerC
ase()
Converts a string to lowercase letters, according to the host's
locale
toLocaleUpperC Converts a string to uppercase letters, according to the host's
ase() locale
toLowerCase() Converts a string to lowercase letters
toString() Returns the value of a String object
toUpperCase() Converts a string to uppercase letters
trim() Removes whitespace from both ends of a string
valueOf() Returns the primitive value of a String object


2.8 Document Object Model:
Every web page resides inside a browser window which can be considered as an object.
A Document object represents the HTML document that is displayed in that window. The
Document object has various properties that refer to other objects which allow access to
and modification of document content.
The way that document content is accessed and modified is called the Document Object
Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure
applies to the organization of objects in a Web document.
Window object: Top of the hierarchy. It is the outmost element of the object hierarchy.
Document object: Each HTML document that gets loaded into a window becomes a
document object. The document contains the content of the page.
Form object: Everything enclosed in the <form>...</form> tags sets the form object.
Form control elements: The form object contains all the elements defined for that object
such as text fields, buttons, radio buttons, and checkboxes.




Here is a simple hierarchy of few important objects:






2.9 Java Script Event Handling:
Event Handlers
The simplest way to run JavaScript code in response to an event is to use an event
handler. Event handlers have been around for as long as browsers have supported
JavaScript, and predate the DOM standard. An event handler is a JavaScript function
thats plugged into a node in the DOM so that its called automatically when a
particular event occurs in relation to that element.


Setting up a function as an event handler is easy. All you need is a reference to the DOM
element for which you want to handle events. Then, you set the elements onevent
property, where event is the type of event you want to handle:
element.onevent = eventHandler;
we cant assign an event handler to our element until the element has loaded.




The browser encounters the <script>tag in the HTML documents header and loads the
JavaScript file.

1. Our code declares the Link object, then calls Core.start to request that the
objects init method be called when the whole document has loaded.

2. The page finishes loading, and the Link objects init method is called. This method finds the
link and sets up the clickHandler method as its click event handler.
3. The user clicks the link, which generates a click event. The browser calls clickHandler, the
links click event handler


Some of the events on which the JavaScript Programming can be carried out are listed as
below:








2.9 Forms in JavaScript:
The HTML Form object serves a number of purposes. It acts a container for all of the GUI
objects that make up a form. It also acts as the mechanism for grouping together the information
provided by the user and sending it back to the server for processing.
The <form> takes a number of attributes of which the following are the most commonly used:
name - the name of the form, which will be used when referencing objects within the form
using JavaScript code.
method - the method by which data is sent to the server. This will either be "GET" or
"POST" depending on the server-side configuration.
action - the URL of the CGI script to which the data entered by the user will be sent. It is
also possible to use mailto: to have the data sent to an email address.
onsubmit - an optional function to call, or inline script to execute before the form data is
submitted to the server. This can be useful for validating user input.
The following is an example of a Form object named registerForm which submits the user data
to a cgi script called register.cgi located in the /cgi-bin directory on the server which hosts the
web site. The transfer is configured to use the GET method:

<form name="registerForm" method="GET" action="/cgi-bin/register.cgi">

<-- Form Objects go here -->

</form>

Accessing Objects in a Form
the Form object is really just a container which contains other objects (such as text fields
and buttons).
One way to access the elements in a Form is to use the Form object's elements property. This is
an array containing all the objects in a Form (see JavaScript Arrays for details on arrays). We
can, therefore, access any element in the array by using the index (note that the objects in the
array are in the order in which they are specified in the Form). Suppose we have a text object
which is the first object inside a Form called myForm:

<form action="" name="myForm">
<input type="TEXT" name="phoneNumber" id="phoneNumber" value="" />
</form>

We can access this object as follows:

document.myForm.elements[0];

We can then extend this to get the current value entered into the text object:

textValue = document.myForm.elements[0].value;

A much easier approach is to access the object using the name that was assigned to it at creation.
This is achieved using thegetElementById() method. Assuming in our first example the Text
object was assigned a name of phoneNumber we could assign the object to a variable as follows:

phone = document.getElementById("phoneNumber");

We can then subsequently use the phone variable to access the current text value entered into the
text field object:

document.write ( "The text is " + phone.value );


JavaScript and the Text Object
The most common of these objects is the Text object. The Text object places a single line text
field into the form into which the user can type information (such a name, address or telephone
number).
The syntax for creating a text object within a Form is as follows:
<input type="TEXT" name="objectname" id="object id" value="current value"
size="30" event handling>
type - specifies that the type of object is a TEXT object.
name - represents the name by which this object may be reference in JavaScript.
id - the id used when accessing Form object elements using thegetElementById() method
(described later in this chapter)
value - primes the text object with an initial value (optional).
size - specifies the maximum number of characters that can be entered into the Text field.

event handling specifies what action to take when a particular event on the object is triggered.
Events that can be triggered by the Text object are:
onFocus - triggered when the text field gains focus (typically when the cursor is moved into
the field to begin typing).
onBlur - triggered when the text field loses focus (typically when the user clicks somewhere
outside the text area).
onChange - triggered when the contents of the text area is changed by the user and focus is
lost.
onSelect - triggered when the user highlights text in the text field.
In addition to events, the Text object also has a number of methods that can be accessed to
perform such tasks as selecting text and changing focus:
focus() - sets focus and sets the cursor on the text field
blur() - Removes focus from the field (the opposite of focus())
select() - Selects the text in the field so that when the user types all the existing text is
replaced.

Now that we have covered some of the basics of building a FORM we can bring some of these
concepts together in an example using the text object. The following example creates a Form
containing a text field. When the user clicks in the text field the onFocus event is triggered
which, in turn, calls the select() method to highlight the text in the field. Note that since we are
referencing the current object when calling the select() method we can use the this keyword to
refer to the current object:

<html>
<head>
<title>JavaScript Form Example</title>
<script language=javascript type="text/javascript">
function buttonPressed()
{
// document.write ( document.myForm.elements[0].value );
var phone = document.getElementById("myText");

document.write ( phone.value );
}
</script>
</head>

<body>

<form action="" name="myForm">
<input type="TEXT" name="myText" id="myText" value="Some text"
onFocus="this.select()"/>
</form>

</body>
</html>

JavaScript and The Button Object
There are three types of Button object available. As with the Text object the
Button objects use the <input> tag. The type=attribute is then used to define which type of
button is to be created. The three different types are:
type="BUTTON" - The basic button which performs no action by default unless
an event handler is assigned to it.
type="SUBMIT" - The submit button. When pressed this button causes the data in the Form
to be sent to the server using the settings defined in the enclosing <Form> tag. If
the onsubmit attribute on the enclosing <form> tag has been specified this will be executed
before the form data is submitted (useful for form data validation).
type="RESET" - The reset button. When pressed causes the fields in the Form to be either
cleared, or reset to the defaultValue (if one has been specified).
A submit button can be created as follows:

<form name="registerForm" method="GET" action="/cgi-bin/register.cgi">

<input type="TEXT" name="myName" value=""/>
<input type="TEXT" name="myPhone" value=""/>
<input type="SUBMIT" name="buttonName" value="Click here to submit information">

</form>

When the submit button is pressed in the above example the data in the two Text fields will be
submitted to the register.cgi script specified in the <form> tag.
The generic "BUTTON" type can be defined as follows:

<form name="registerForm" method="GET" action="/cgi-bin/register.cgi">

<input type="TEXT" name="myName" value=""/>
<input type="TEXT" name="myPhone" value=""/>
<input type="BUTTON" name="buttonName" value="Product codes"
onClick="showCodes()">

</form>

JavaScript Check Boxes
The Check Box object creates a small square that changes between a checked and unchecked
state when clicked. Check Boxes are ideal for providing the user with a "Yes" or "No" choice.
The Check Box object uses the <input> tag as follows:
<form action="" name="orderForm">
<input type="CHECKBOX" name="mailListBox" checked>Add me to the mailing List.
</form>
The checked attribute states whether the box should be checked by default when it is first
created.
The current setting of a CheckBox can be obtained by accessing the checked property of the
object. For example:
if (document.orderForm.mailListBox.checked)
{
addToMailingList();
}
You can also change the state of a Check Box by explicitly setting the checked property:

document.orderForm.mailListBox.checked = false;

The Check Box object has one event, onClick, which is triggered when the user clicks on the
box, and one method, click(), which simulates a user click when called.
JavaScript and Radio Buttons
The Radio Button object takes its name from the buttons on an old radio. In the old days a radio
would a have a number of buttons for making selections (such as frequency band). Depressing
one button would cause the currently selected button to pop up, thereby ensuring that only one
button was pressed at any one time. JavaScript Radio Buttons provide a similar functionality for
situations where a "one of many" choice is to be presented to the user.
The syntax for creating a group of Radio Buttons is as follows:
<form action="" name="orderForm">
<input type="RADIO" name="myColor" value="Red" checked> Red
<input type="RADIO" name="myColor" value="Green"> Green
<input type="RADIO" name="myColor" value="Blue"> Blue
</form>
JavaScript and Drop-down / Select Object
The Select object provides a drop down list of choices from which the user can choose (often
referred to as ComboBoxes in other GUI environments). When the drop down list is not visible
the current selection is displayed in a text area. Due to the fact that the Select Object supports
both single and multiple selection of items in the list it is ideal for both "one of many" and "many
of many" selection choices.
The Select Object uses the <select> tag together with <option> tags representing the choices to
be displayed in the drop-down list:

<select name="carBrands">
<option value="Ford" SELECTED>Ford Motor Company
<option value="GM">General Motors
<option value="Honda">Honda Motor Company
</select>

Objective Questions:

Options
- True
- False

CORRECT ANSWER : False






















Unit III
ASP: Active server Pages

Learning Objectives:

After studying this unit, you should be able to :
Understand the Basic concepts of ASP
Describe programming features of ASP
Define the ASP Operators & variables
Describe the Looping & Conditional statements
Define Static and Dynamic Arrays
Describe Procedures and forms controls


3.1 Introduction:
ASP stands for Active Server Pages. Microsoft introduced Active Server Pages in December
1996, beginning with Version 3.0. Microsoft officially defines ASP as:
Active Server Pages is an open, compile-free application environment in which you can
combine HTML, scripts, and reusable ActiveX server components to create dynamic and
powerful Web-based business solutions. Active Server pages enables server side scripting for IIS
with native support for both VBScript and Jscript. . In other words, ASP is a Microsoft
technology that enables you to create dynamic web sites with the help of server side script, such
as VBScript and Jscript.
ASP technology is supported on all Microsoft Web servers that are freely available.
ASP stands for Active Server Pages
ASP is a Microsoft Technology
ASP is a program that runs inside IIS
IIS stands for Internet Information Services
IIS comes as a free component with Windows 2000
IIS is also a part of the Windows NT 4.0 Option Pack

3.2 Some of the advantages of the ASP are:
Dynamically edit, change, or add any content of a Web page
Respond to user queries or data submitted from HTML forms
Access any data or databases and return the results to a browser
Customize a Web page to make it more useful for individual users
The advantages of using ASP instead of CGI and Perl, are those of simplicity and speed
Provide security - since ASP code cannot be viewed from the browser
Clever ASP programming can minimize the network traffic
Method to run ASP on computer:
To allow a user to access an ASP, the ability to do so must be enabled on the IIS server.
IIS or Personal Web Server, of Microsoft must be downloaded on the computer.
When you are creating an Active Server Page, the server-side script can be identified in one of
the following two ways:
Use the server-side script block identifiers <% and %>.
Use the <SCRIPT> tag with the RUNAT=SERVER attribute.
An ASP file normally contains HTML tags, just like an HTML file. However, an ASP
file can also contain server scripts, surrounded by the delimiters <% and %>.
Server scripts are executed on the server, and can contain any expressions, statements,
procedures, or operators valid for the scripting language you prefer to use.

3.3 The Response.Write Command
The Response.Write command is used to write output to a browser. The following
example sends the text "Hello World" to the browser:
In VbScript:
<!DOCTYPE html>
<html>
<body>
<%
response.write("Hello World!")
%>
</body>
</html>

In JavaScript
<%@ language="javascript"%>
<!DOCTYPE html>
<html>
<body>
<%
Response.Write("Hello World!")
%>
</body>
</html>

3.4 Procedures
The ASP source code can contain procedures and functions:
VbScript:
<!DOCTYPE html>
<html>
<head>
<%
sub vbproc(num1,num2)
response.write(num1*num2)
end sub
%>
</head>
<body>

<p>Result: <%call vbproc(3,4)%></p>

</body>
</html>


JavaScript:
<%@ language="javascript" %>
<!DOCTYPE html>
<html>
<head>
<%
function jsproc(num1,num2)
{
Response.Write(num1*num2)
}
%>
</head>
<body>

<p>Result: <%jsproc(3,4)%></p>

</body>
</html>

3.5 ASP Forms and User Input

The Request.QueryString and Request.Form commands are used to retrieve user input from
forms.
The Request object can be used to retrieve user information from forms.
Example HTML form
<form method="get" action="simpleform.asp">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br><br>
<input type="submit" value="Submit">
</form>
User input can be retrieved with the Request.QueryString or Request.Form command.

Request.QueryString
The Request.QueryString command is used to collect values in a form with method="get".
Information sent from a form with the GET method is visible to everyone (it will be displayed in
the browser's address bar) and has limits on the amount of information to send.
If a user typed "Bill" and "Gates" in the HTML form above, the URL sent to the server would
look like this:
http://www.w3schools.com/simpleform.asp?fname=Bill&lname=Gates
Assume that "simpleform.asp" contains the following ASP script:
<body>
Welcome
<%
response.write(request.querystring("fname"))
response.write(" " & request.querystring("lname"))
%>
</body>
The browser will display the following in the body of the document:
Welcome Bill Gates

Request.Form
The Request.Form command is used to collect values in a form with method="post".
Information sent from a form with the POST method is invisible to others and has no limits on
the amount of information to send.
If a user typed "Bill" and "Gates" in the HTML form above, the URL sent to the server would
look like this:
http://www.w3schools.com/simpleform.asp
Assume that "simpleform.asp" contains the following ASP script:
<body>
Welcome
<%
response.write(request.form("fname"))
response.write(" " & request.form("lname"))
%>
</body>
The browser will display the following in the body of the document:
Welcome Bill Gates

The VBScript arrays are 0 based, meaning that the array element indexing starts always from 0.
The 0 index represents the first position in the array, the 1 index represents the second position in
the array, and so forth.
There are two types of VBScript arrays - static and dynamic. Static arrays remain with fixed size
throughout their life span. To use static VBScript arrays you need to know upfront the maximum
number of elements this array will contain. If you need more flexible VBScript arrays with
variable index size, then you can use dynamic VBScript arrays. VBScript dynamic arrays index
size can be increased/decreased during their life span.
3.6 Arrays in ASP:
(a) Static Arrays
Let's create an array called 'arrCars' that will hold the names of 5 cars:
<%@ LANGUAGE="VBSCRIPT" %>
<%
'Use the Dim statement along with the array name
'to create a static VBScript array
'The number in parentheses defines the arrays upper bound
Dim arrCars(4)
arrCars(0)="BMW"
arrCars(1)="Mercedes"
arrCars(2)="Audi"
arrCars(3)="Bentley"
arrCars(4)="Mini"

'create a loop moving through the array
'and print out the values
For i=0 to 4
response.write arrCars(i) & "<br>"
Next 'move on to the next value of i
%>

<%
Dim arrCars
arrCars = Array("BMW","Mercedes","Audi","Bentley","Mini") 'each element must be separated
by a comma

'again we could loop through the array and print out the values
For i=0 to 4
response.write arrCars(i) & "<br>"
Next
%>
(b) Dynamic Arrays
Dynamic arrays come in handy when you aren't sure how many items your array will hold. To
create a dynamic array you should use the Dim statement along with the arrays name, without
specifying upper bound:
<%
Dim arrCars
arrCars = Array()
%>
In order to use this array you need to use the ReDim statement to define the arrays upper bound:
<%
Dim arrCars
arrCars = Array()
Redim arrCars(27)
%>
When you use the ReDim statement you lose all elements of the array. Using the keyword
PRESERVE in conjunction with the ReDim statement will keep the array we already have and
increase the size:
<%
Dim arrCars
arrCars = Array()
Redim arrCars(27)
Redim PRESERVE arrCars(52)
%>

3.7 Functions & Procedures
Functions and procedures provide a way to create re-usable modules of programming code and
avoid rewriting the same block of code every time you do the particular task. If you don't have
any functions/procedures in your ASP page, the ASP pages are executed from top to bottom, the
ASP parsing engine simply processes your entire file from the beginning to the end.
ASP/VBScript functions and procedures, however, are executed only when called, not inline
with the rest of the code. A function or subprocedure can be reused as many times as required,
thus saving you time and making for a less clustered looking page.
You can write functions in ASP similar to the way you write them in Visual Basic. It is good
programming practice to use functions to modularize your code and to better provide reuse. To
declare a subroutine (a function that doesnt return a value, starts with the Sub keyword and ends
with End Sub), you simply type:
<%@ LANGUAGE="VBSCRIPT" %>
<%
Sub subroutineName( parameter_1, ... , parameter_n )
statement_1
statement_2
...
statement_n
end sub
%>
A function differs from a subroutine in the fact that it returns data, start with Function keyword
and end with End Function. Functions are especially good for doing calculations and returning a
value. To declare a function, the syntax is similar:
<%@ LANGUAGE="VBSCRIPT" %>
<%
Function functionName( parameter_1, ... , parameter_n )
statement_1
statement_2
...
statement_n
end function
%>
<%@ LANGUAGE="VBSCRIPT" %>
<%
Sub GetInfo(name, phone, fee)
Response.write("Name: "& name &"<br>")
Response.write("Telephone: "& telephone &"<br>")
Response.write("Fee: "& fee &"<br>")
End Sub
%>
Now let's consider how to call the sub. There are two ways:
<%
'the first method
Call GetInfo("Mr. O'Donnel","555-5555",20)
'the second one
GetInfo "Mr. O'Donnel","555-5555",20
%>
In each example, the actual argument passed into the subprocedure is passed in the
corresponding position. Note that if you use the Call statement, the arguments must be enclosed
in parentheses. If you do not use call, the parentheses aren't used.
Now let's look at the code for a function that takes an integer value and returns the square of that
value. Also included is code to call the function.
<%
Function Square(num)
Square = num * num
end function

'Returns 25
Response.Write(Square(5))

'Should print "45 is less than 8^2"
if 40 < Square(7) then
Response.Write("45 is less than 8^2")
else
Response.Write("8^2 is less than 40")
end if
%>
To return a value from a function, you need to name the output value the same as your function
or you will not get a value returned.


3.8 Looping Statements:
ASP performs several types of repetitive operations, called "looping". Loops are set of
instructions used to repeat the same block of code till a specified condition returns false or true
depending on how you need it. To control the loops you can use counter variable that increments
or decrements with each repetition of the loop.
The two major groups of loops are For..Next and Do..Loop. The For...Next statements are best
used when you want to perform a loop a specific number of times. The Do...Loop statements are
best used to perform a loop an undetermined number of times. In addition, you can use the Exit
keyword within loop statements.
The For ... Next Loop
The For Each ... Next Loop
The Do ... Loop
The Exit Keyword

(a) The For ... Next Loop
For...Next loops are used when you want to execute a piece of code a set number of times. The
syntax is as follows:
For counter = initial_value to finite_value [Step increment]
statements
Next
The For statement specifies the counter variable and its initial and finite values. The Next
statement increases the counter variable by one. Optional the Step keyword allows to increase or
decrease the counter variable by the value you specify.
Have a look at the very simple example:
<%@ language="vbscript" %>
<%
For i = 0 to 10 Step 2 'use i as a counter
response.write("The number is " & i & "<br />")
Next
%>
The preceding example prints out even numbers from 0 to 10, the <br> tag puts a line break in
between each value.
Next example generates a multiplication table 2 through 9. Outer loop is responsible for
generating a list of dividends, and inner loop will be responsible for generating lists of dividers
for each individual number:
<%@ language="vbscript" %>
<%
response.write("<h1>Multiplication table</h1>")
response.write("<table border=2 width=50%")

For i = 1 to 9 'this is the outer loop
response.write("<tr>")
response.write("<td>" & i & "</td>")

For j = 2 to 9 'inner loop
response.write("<td>" & i * j & "</td>")
Next 'repeat the code and move on to the next value of j

response.write("</tr>")
Next 'repeat the code and move on to the next value of i

response.write("</table>")
%>
(b) The For Each ... Next Loop
The For Each...Next loop is similar to a For...Next loop. Instead of repeating the statements a
specified number of times, the For Each...Next loop repeats the statements for each element of an
array (or each item in a collection of objects).
The following code snippet creates drop-down list where options are elements of an array:
<%
Dim bookTypes(7) 'creates first array
bookTypes(0)="Classic"
bookTypes(1)="Information Books"
bookTypes(2)="Fantasy"
bookTypes(3)="Mystery"
bookTypes(4)="Poetry"
bookTypes(5)="Humor"
bookTypes(6)="Biography"
bookTypes(7)="Fiction"

Dim arrCars(4) 'creates second array
arrCars(0)="BMW"
arrCars(1)="Mercedes"
arrCars(2)="Audi"
arrCars(3)="Bentley"
arrCars(4)="Mini"

Sub createList(some_array) 'takes an array and creates drop-down list
dim i
response.write("<select name=""mylist"">" & vbCrLf) 'vbCrLf stands for Carriage Return and
Line Feed
For Each item in some_array
response.write("<option value=" & i & ">" & item & "</option>" & vbCrLf)
i = i + 1
Next 'repeat the code and move on to the next value of i
response.write("</select>")
End Sub

'Now let's call the sub and print out our lists on the screen
Call createList(bookTypes) 'takes bookTypes array as an argument
Call createList(arrcars) 'takes arrCars array as an argument
%>
(c) The Do ... Loop
The Do...Loop is another commonly used loop after the For...Next loop. The Do...Loop
statement repeats a block of statements an indefinite number of times. The statements are
repeated either while a condition is True or until a condition becomes True. The syntax looks as
follows:
Do [While|Until] condition
statements
Loop
Here is another syntax:
Do
statements
Loop [While|Until] condition
In this case the code inside this loop will be executed at least one time. Have a look at the
examples:
The example below defines a loop that starts with i=0. The loop will continue to run as long as i
is less than, or equal to 10. i will increase by 1 each time the loop runs.
<%
Dim i 'use i as a counter
i = 0 'assign a value to i

Do While i<=10 'Output the values from 0 to 10
response.write(i & "<br \>")
i = i + 1 'increment the value of i for next time loop executes
Loop
%>
Now let's consider a more useful example which creates drop-down lists of days, months and
years. You can use this code for registration form, for example.
<%
'creates an array
Dim month_array(11)
month_array(0) = "January"
month_array(1) = "February"
month_array(2) = "March"
month_array(3) = "April"
month_array(4) = "May"
month_array(5) = "June"
month_array(6) = "July"
month_array(7) = "August"
month_array(8) = "September"
month_array(9) = "October"
month_array(10) = "November"
month_array(11) = "December"

Dim i 'use i as a counter

response.write("<select name=""day"">" & vbCrLf)
i = 1
Do While i <= 31
response.write("<option value=" & i & ">" & i & "</option>" & vbCrLf)
i = i + 1
Loop
response.write("</select>")

response.write("<select name=""month"">" & vbCrLf)
i = 0
Do While i <= 11
response.write("<option value=" & i & ">" & month_array(i) & "</option>" & vbCrLf)
i = i + 1
Loop
response.write("</select>")

response.write("<select name=""year"">")
i = 1900
Do Until i = 2005
response.write("<option value=" & i & ">" & i & "</option>" & vbCrLf)
i = i + 1
Loop
response.write("</select>")
%>
(d) The Exit Keyword
The Exit keyword alters the flow of control by causing immediate exit from a repetition
structure. You can use the Exit keyword in different situations, for example to avoid an endless
loop. To exit the For...Next loop before the counter reaches its finite value you should use the
Exit For statement. To exit the Do...Loop use the Exit Do statement.
<%
response.write("<p><strong>Example of using the Exit For statement:</strong><p>")

For i = 0 to 10
If i=3 Then Exit For
response.write("The number is " & i & "<br />")
Next

response.write("<p><strong>Example of using the Exit Do statement:</strong><p>")

i = 5
Do Until i = 10
i = i - 1
response.write("The number is " & i & "<br />")
If i < 10 Then Exit Do
Loop
%>














UNIT IV
ASP with ADO
Learning Objectives:

After studying this unit, you should be able to :
Describe ADO
Describe how to access the database from an ASP page
Define the ADO connection with the ASP
Describe how to display, add, sort and delete records from an ASP pages through ADO


4.1 Introduction
The great advantage of ASP is possibility to respond to user queries or data submitted from
HTML forms. You can process information gathered by an HTML form and use ASP code to
make decisions based off this information to create dynamic web pages. In this tutorial we will
show how to create an HTML form and process the data.
Before you can process the information, you need to create an HTML form that will send
information to your ASP page. There are two methods for sending data to an ASP form: POST
and GET. These two types of sending information are defined in your HTML form element's
method attribute. Also, you must specify the location of the ASP page that will process the
information.
Below is a simple form that will send the data using the POST method. Information sent from a
form with the POST method is invisible to others and has no limits on the amount of information
to send. Copy and paste this code and save it as "form.html".
<html>
<head>
<title>Process the HTML form data with the POST method</title>
</head>
<body>
<form method="POST" action="process.asp" name="form1">
<table width="70%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>name:</td>
<td colspan="2"><input type="text" name="name"></td>
</tr>
<tr>
<td>email:</td>
<td colspan="2"><input type="text" name="email"></td>
</tr>
<tr>
<td>comments:</td>
<td colspan="2"><textarea name="comment" cols="40" rows="5"></textarea></td>
</tr>
<tr>
<td>&nbsp;</td>
<td colspan="2"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
Next, we are going to create our ASP page "process.asp" that will process the data. In our
example we decided to send data with the POST method so to retrieve the information we
can use the ASP 'Request.From' command. Copy and paste this code and save it in the same
directory as "form.html".
<%@ Language="VBscript" %>
<html>
<head>
<title>Submitted data</title>
</head>

<body>
<%
'declare the variables that will receive the values
Dim name, email, comment
'receive the values sent from the form and assign them to variables
'note that request.form("name") will receive the value entered
'into the textfield called name
name=Request.Form("name")
email=Request.Form("email")
comment=Request.Form("comment")

'let's now print out the received values in the browser
Response.Write("Name: " & name & "<br>")
Response.Write("E-mail: " & email & "<br>")
Response.Write("Comments: " & comment & "<br>")
%>
</body>
</html>


4.2 Creating an Instance of Connection Object
The power of Active Server Pages comes through when we tie databases to our web sites. To
connect to a database, ASP uses what is called ActiveX Data Objects, or ADO for short. ADO
comes with ASP, and can be used easily from your ASP pages.
First we must create an instance of the connection object and feed it the location of the database
we wish to connect to and the driver that we intend to use. For these purposes we will use
a connection string. You can choose an ODBC or an OLEDB connection string. We will use
OLEDB for our example as it's faster and more stable. Next, we should open the connection to
the database:
<%
'declare the variable that will hold new connection object
Dim Connection
'create an ADO connection object
Set Connection=Server.CreateObject("ADODB.Connection")

'declare the variable that will hold the connection string
Dim ConnectionString
'define connection string, specify database driver and location of the database
ConnectionString="PROVIDER=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source= c:\inetpub\wwwroot\db\examples.mdb"

'open the connection to the database
Connection.Open ConnectionString
%>
Great, now we have an active connection to our database. Let's retrieve all the records from the
'Cars' table. For that we have to create an instance of the recordset object and feed it an SQL
statement.
<%
'declare the variable that will hold our new object
Dim Recordset
'create an ADO recordset object
Set Recordset=Server.CreateObject("ADODB.Recordset")

'declare the variable that will hold the SQL statement
Dim SQL
SQL="SELECT * FROM CARS"

'Open the recordset object executing the SQL statement and return records
Recordset.Open SQL, Connection
%>
We have returned a recordset based on our SQL statement so let's now print out them in the
browser.
<%
'first of all determine whether there are any records
If Recordset.EOF Then
Response.Write("No records returned.")
Else
'if there are records then loop through the fields
Do While NOT Recordset.Eof
Response.write Recordset("Name")
Response.write Recordset("Year")
Response.write Recordset("Price")
Response.write "<br>"
Recordset.MoveNext
Loop
End If
%>
Finally, need to close the objects and free up resources on the server.
<%
Recordset.Close
Set Recordset=Nothing
Connection.Close
Set Connection=Nothing
%>
4.3 Connection Strings
Connection strings are string variables which contain database connection information and then
passed to ADO(ActiveX Data Objects) which will interpret them and act accordingly. Since
there are going to be passed to ADO, they need to be in a comprehensible for ADO format.
Connection string contains several arguments set to specific values and separated by semicolon.
If you are connecting to a SQL database, you need the DRIVER, the SERVER, the
DATABASE, the UID, the PWD, and other optional information. If you're connecting to an
Access database, you need the DRIVER, and the DBQ, and some other optional information.
MS Access Connection Strings
SQL Server Connection Strings
MySQL Connection Strings
Oracle Connection Strings






to create a System Data Source Name (DSN) for an Access database on your local
machine. To do that you need to follow a couple of steps:
Open the 'ODBC Data Source Administrator'
( Start -> Control Panel -> Administrative Tools -> Data Sources )
Flip to the System DSN tab

Click Add...

In the box that will appear you should select the Microsoft Access driver and click
Finish
Type in a name that is easily remembered and relevant to your database in the 'Data
Source Name' textbox

Click Select and browse to your local database file

Click OK all the way out
You have now created a DSN which will come in handy when you try to connect and
retrieve information from your database.

4.4 Connection Using DSN
DSN stands for 'Data Source Name'. It is an easy way to assign useful and easily
rememberable names to data sources which may not be limited to databases alone.
<%
'declare the variables
Dim Connection
Dim Recordset
Dim SQL

'declare the SQL statement that will query the database
SQL = "SELECT * FROM TABLE_NAME"

'create an instance of the ADO connection and recordset objects
Set Connection = Server.CreateObject("ADODB.Connection")
Set Recordset = Server.CreateObject("ADODB.Recordset")

'open the connection to the database
Connection.Open
"DSN=dsn_name;UID=user_name;PWD=password;Database=database_name"

'Open the recordset object executing the SQL statement and return records
Recordset.Open SQL,Connection

'first of all determine whether there are any records
If Recordset.EOF Then
Response.Write("No records returned.")
Else
'if there are records then loop through the fields
Do While NOT Recordset.Eof
Response.write Recordset("FIRST_FIELD_NAME")
Response.write Recordset("SECOND_FIELD_NAME")
Response.write Recordset("THIRD_FIELD_NAME")
Response.write "<br>"
Recordset.MoveNext
Loop
End If

'close the connection and recordset objects to free up resources
Recordset.Close
Set Recordset=nothing
Connection.Close
Set Connection=nothing
%>



Connect without a DSN (using a connection string)
Lets look at a sample script to get an idea how to connect to MS SQL Server database without
DSN:
<%
'declare the variables
Dim Connection
Dim ConnString
Dim Recordset
Dim SQL

'define the connection string, specify database driver
ConnString="DRIVER={SQL Server};SERVER=yourServername;UID=yourUsername;" & _
"PWD=yourPassword;DATABASE=yourDatabasename"

'declare the SQL statement that will query the database
SQL = "SELECT * FROM TABLE_NAME"

'create an instance of the ADO connection and recordset objects
Set Connection = Server.CreateObject("ADODB.Connection")
Set Recordset = Server.CreateObject("ADODB.Recordset")

'Open the connection to the database
Connection.Open ConnString

'Open the recordset object executing the SQL statement and return records
Recordset.Open SQL,Connection

'first of all determine whether there are any records
If Recordset.EOF Then
Response.Write("No records returned.")
Else
'if there are records then loop through the fields
Do While NOT Recordset.Eof
Response.write Recordset("FIRST_FIELD_NAME")
Response.write Recordset("SECOND_FIELD_NAME")
Response.write Recordset("THIRD_FIELD_NAME")
Response.write "<br>"
Recordset.MoveNext
Loop
End If

'close the connection and recordset objects to free up resources
Recordset.Close
Set Recordset=nothing
Connection.Close
Set Connection=nothing
%>

4.5 Add a Record to a Table in a Database
We want to add a new record to the Customers table in the Northwind database. We first create a
form that contains the fields we want to collect data from:
<html>
<body>

<form method="post" action="demo_add.asp">
<table>
<tr>
<td>CustomerID:</td>
<td><input name="custid"></td>
</tr><tr>
<td>Company Name:</td>
<td><input name="compname"></td>
</tr><tr>
<td>Contact Name:</td>
<td><input name="contname"></td>
</tr><tr>
<td>Address:</td>
<td><input name="address"></td>
</tr><tr>
<td>City:</td>
<td><input name="city"></td>
</tr><tr>
<td>Postal Code:</td>
<td><input name="postcode"></td>
</tr><tr>
<td>Country:</td>
<td><input name="country"></td>
</tr>
</table>
<br><br>
<input type="submit" value="Add New">
<input type="reset" value="Cancel">
</form>

</body>
</html>
When the user presses the submit button the form is sent to a file called "demo_add.asp". The
"demo_add.asp" file contains the code that will add a new record to the Customers table:
<html>
<body>

<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"

sql="INSERT INTO customers (customerID,companyname,"
sql=sql & "contactname,address,city,postalcode,country)"
sql=sql & " VALUES "
sql=sql & "('" & Request.Form("custid") & "',"
sql=sql & "'" & Request.Form("compname") & "',"
sql=sql & "'" & Request.Form("contname") & "',"
sql=sql & "'" & Request.Form("address") & "',"
sql=sql & "'" & Request.Form("city") & "',"
sql=sql & "'" & Request.Form("postcode") & "',"
sql=sql & "'" & Request.Form("country") & "')"

on error resume next
conn.Execute sql,recaffected
if err<>0 then
Response.Write("No update permissions!")
else
Response.Write("<h3>" & recaffected & " record added</h3>")
end if
conn.close
%>

</body>
</html>

4.6 Update a Record in a Table
We want to update a record in the Customers table in the Northwind database. We first create a
table that lists all records in the Customers table:
<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM customers",conn
%>

<h2>List Database</h2>
<table border="1" width="100%">
<tr>
<%
for each x in rs.Fields
response.write("<th>" & ucase(x.name) & "</th>")
next
%>
</tr>
<% do until rs.EOF %>
<tr>
<form method="post" action="demo_update.asp">
<%
for each x in rs.Fields
if lcase(x.name)="customerid" then%>
<td>
<input type="submit" name="customerID" value="<%=x.value%>">
</td>
<%else%>
<td><%Response.Write(x.value)%></td>
<%end if
next
%>
</form>
<%rs.MoveNext%>
</tr>
<%
loop
conn.close
%>
</table>

</body>
</html>
If the user clicks on the button in the "customerID" column he or she will be taken to a new file
called "demo_update.asp". The "demo_update.asp" file contains the source code on how to
create input fields based on the fields from one record in the database table. It also contains a
"Update record" button that will save your changes:
<html>
<body>

<h2>Update Record</h2>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"

cid=Request.Form("customerID")

if Request.form("companyname")="" then
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM customers WHERE customerID='" & cid & "'",conn
%>
<form method="post" action="demo_update.asp">
<table>
<%for each x in rs.Fields%>
<tr>
<td><%=x.name%></td>
<td><input name="<%=x.name%>" value="<%=x.value%>"></td>
<%next%>
</tr>
</table>
<br><br>
<input type="submit" value="Update record">
</form>
<%
else
sql="UPDATE customers SET "
sql=sql & "companyname='" & Request.Form("companyname") & "',"
sql=sql & "contactname='" & Request.Form("contactname") & "',"
sql=sql & "address='" & Request.Form("address") & "',"
sql=sql & "city='" & Request.Form("city") & "',"
sql=sql & "postalcode='" & Request.Form("postalcode") & "',"
sql=sql & "country='" & Request.Form("country") & "'"
sql=sql & " WHERE customerID='" & cid & "'"
on error resume next
conn.Execute sql
if err<>0 then
response.write("No update permissions!")
else
response.write("Record " & cid & " was updated!")
end if
end if
conn.close
%>

</body>
</html>

4.7 Delete a Record in a Table
We want to delete a record in the Customers table in the Northwind database. We first create a
table that lists all records in the Customers table:
<html>
<body>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM customers",conn
%>

<h2>List Database</h2>
<table border="1" width="100%">
<tr>
<%
for each x in rs.Fields
response.write("<th>" & ucase(x.name) & "</th>")
next
%>
</tr>
<% do until rs.EOF %>
<tr>
<form method="post" action="demo_delete.asp">
<%
for each x in rs.Fields
if x.name="customerID" then%>
<td>
<input type="submit" name="customerID" value="<%=x.value%>">
</td>
<%else%>
<td><%Response.Write(x.value)%></td>
<%end if
next
%>
</form>
<%rs.MoveNext%>
</tr>
<%
loop
conn.close
%>
</table>

</body>
</html>
If the user clicks on the button in the "customerID" column he or she will be taken to a new file
called "demo_delete.asp". The "demo_delete.asp" file contains the source code on how to create
input fields based on the fields from one record in the database table. It also contains a "Delete
record" button that will delete the current record:
<html>
<body>

<h2>Delete Record</h2>
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/northwind.mdb"

cid=Request.Form("customerID")

if Request.form("companyname")="" then
set rs=Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM customers WHERE customerID='" & cid & "'",conn
%>
<form method="post" action="demo_delete.asp">
<table>
<%for each x in rs.Fields%>
<tr>
<td><%=x.name%></td>
<td><input name="<%=x.name%>" value="<%=x.value%>"></td>
<%next%>
</tr>
</table>
<br><br>
<input type="submit" value="Delete record">
</form>
<%
else
sql="DELETE FROM customers"
sql=sql & " WHERE customerID='" & cid & "'"
on error resume next
conn.Execute sql
if err<>0 then
response.write("No update permissions!")
else
response.write("Record " & cid & " was deleted!")
end if
end if
conn.close
%>

</body>
</html>






















Unit V
XML

Learning Objectives:

After studying this unit, you should be able to :
Describe XML
Describe the Features of XML
Define the XML Markup Elements
Understand the markup Languages
Define XML Element Occurrence Indicators
Developing a DTD


5.1 Introduction
If XML markup is a structural language for a document, and tags are the Important elements for
the structure. They mark the boundaries of elements, allow insertion of comments and special
instructions, and declare settings for the parsing environment. A parser, the front line
of any program that processes XML, relies on tags to help it break down documents
into discrete XML objects. Elements are the most common XML object type. They break up the
document into
smaller and smaller cells, nesting inside one another like boxes.


Parts of XML document


Features of XML:
Main features of XML:
XML files are text files, which can be managed by any text editor.
XML is very simple, because it has less than 10 syntax rules.
XML is extensible, because it only specifies the structural rules of tags. No specification
on tags them self.
Because of these features, XML offers following advantages
XML provides a basic syntax that can be used to share information between different
kinds of computers, different applications, and different organizations. XML data is
stored in plain text format. This software- and hardware-independent way of storing data
allows different incompatible systems to share data without needing to pass them through
many layers of conversion. This also makes it easier to expand or upgrade to new
operating systems, new applications, or new browsers, without losing any data.
With XML, your data can be available to all kinds of "reading machines" (Handheld
computers, voice machines, news feeds, etc), and make it more available for blind people,
or people with other disabilities.
XML provides a gateway for communication between applications, even applications on
wildly different systems. As long as applications can share data (through HTTP, file
sharing, or another mechanism), and have an XML parser, they can share structured
information that is easily processed. Databases can trade tables, business applications can
trade updates, and document systems can share information.
It supports Unicode, allowing almost any information in any written human language to
be communicated.
It can represent common computer science data structures: records, lists and trees.
Its self-documenting format describes structure and field names as well as specific
values.
The strict syntax and parsing requirements make the necessary parsing algorithms
extremely simple, efficient, and consistent.
Content-based XML markup enhances searchability, making it possible for agents and
search engines to categorize data instead of wasting processing power on context-based
full-text searches.
XML is heavily used as a format for document storage and processing, both online and
offline.
It is based on international standards.
It can be updated incrementally.
It allows validation using schema languages such as XSD and Schematron, which makes
effective unit-testing, firewalls, acceptance testing, contractual specification and software
construction easier.
The hierarchical structure is suitable for most (but not all) types of documents.
It is platform-independent, thus relatively immune to changes in technology.
Forward and backward compatibility are relatively easy to maintain despite changes in
DTD or Schema.
Its predecessor, SGML, has been in use since 1986, so there is extensive experience and
software available.


There are following types of information in an XML file:
1. Processing Instruction: Used to pass an instruction to applications that processing this file.
Processing instructions are written in the following syntax:
<?target instruction?>
where "target" is the name of a target group of applications expected to use this instruction, and
"instruction" is the actual instruction to be passed to those applications.
2. Comments: Used only to comment the XML file. Comments will be ignored by application
that processing this file. Comments are written in the following syntax:
<!--comment-->
where "comment" is the text of comment.
3. XML Elements: Used to present a unit of information, with a name, a optional body, and
optional attributes. Elements are written in the following syntaxes:
<tag/>
<tag attributes/>
<tag>content</tag>
<tag attributes>content</tag>
where "tag" is the name of the element, "content" is a string of text, or text mixed with XML
elements, and "attributes" is one pair of name and value or a list of multiple pairs of name and
value written in the following syntax:
name="value"
name_1="value 1" name_2="value 2" ... name_n="value n"
4. Mixed Text: A string of text, or text mixed with XML elements, used as contents of elements.
Examples of mixed text:
This mixed text only contains characters.
This mixed text <br/>contains characters and <b s="1">elements</b>.
This mixed text contains entities, &amp;, &lt;</b>.
5. XML Entities: Special escape sequences to represent XML reserved characters. XML entities
can be used in element content and attribute values. These are XML pre-defined entities and
reserved characters they are representing:
Entity Character

&amp; &
&apos; '
&gt; >
&lt; <
&quote; "
5. CDATA Section: A section of text in which any XML reserved characters should be treated
as normal characters. CDATA sections are written in the following syntax:
<![CDATA[
text line
...
]]>

Syntax rules of an XML file:
Two XML elements can be nested by including one element as part of the content of the
other element.
There must be only one element, called root element, that is not nested inside any other
elements.
There must be one "xml" processing instruction before the root element.
Values of element attributes must be enclosed within two double quotes.
Element's tag and attribute's name must be made of alphanumeric characters and 4
additional characters: "-", "_", ":", and ".".
"instructions" in a processing instruction must be written in the same syntax as the
attributes of an element.
That's it. As I said earlier, XML syntax is very simple.
A valid XML file:
<?xml version="1.0"?>
<dictionary>
<!-- valid.xml
Copyright (c) 2012, HerongYang.com, All Rights Reserved.
-->
<note>A valid & simple XML</note>
<word>
<name is_acronym="true" language="EN">POP</name>
<definition>Post Office Protocol</definition>
<definition>Point Of Purchase</definition>
</word>
<word>
<update date="2002-12-23"/>
<name is_acronym="yes">XML</name>
<definition>eXtensible Markup Language</definition>
<note>Example:
<![CDATA[<?xml version="1.0"?><p>Hello world!</p>]]>
</note>
</word>
<word>
<update editor="Herong Yang"/>
<name>Markup</name>
<definition>The amount added to the cost price to calculate
the selling price - <i>Webster</i></definition>
</word>
</dictionary>

Here is a simple XML sample file that represents a glossary with only two words defined:
<?xml version="1.0"?>
<!-- dictionary.xml
Copyright (c) 2012, HerongYang.com, All Rights Reserved.
-->
<dictionary>
<word acronym="true">
<name>XML</name>
<definition referenece="Herong&apos;s Notes">eXtensible Markup
Language.</definition>
<update date="2002-12-23"/>
</word>
<word symbol="true">
<name>&lt;/name>
<definition>Mathematical symbol representing the "less than" logical
operation, like: 1&lt;2.</definition>
<definition>Reserved symbol in XML to representing the beginning of
tags, like: <![CDATA[<p>Hello world!</p>]]>
</definition>
</word>
</dictionary>
Note that:
A multiple-line comment is used to show the copyright information.
"dictionary" is the root element.
Attributes are used in elements: "word", "definition" and "update".
"update" is an empty element with no content.
"word" is a nested element, and repeated twice.
Entity "&apos;" is used in attribute "reference".
Entity "&lt;" is used in contents of elements "name" and "definition".
CDATA section is used in the second "definition" of the second "word", in which "<p>"
and "</p>" will not be considered as XML tags any more.
Since XML file don't care about how the tags should be named and what information they should
be carrying, we can re-organize the same information in many ways. For example:
We could move the information from the "date" attribute of "update" element into the
content, and rewrite the "update" like: <update>2002-12-23</update>
We could also move content into an attribute, like: <name is_acronym="true"
value="XML"/>





XML Element:
An XML element is everything from (including) the element's start tag to (including) the
element's end tag.
An element can contain:
other elements
text
attributes
or a mix of all of the above...
<bookstore>
<book category="CHILDREN">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
In the example above, <bookstore> and <book> have element contents, because they contain
other elements. <book> also has an attribute (category="CHILDREN"). <title>, <author>,
<year>, and <price> have text content because they contain text.

Empty XML Elements
An alternative syntax can be used for XML elements with no content:
Instead of writing a book element (with no content) like this:
<book></book>
It can be written like this:
<book />
This sort of element syntax is called self-closing.

XML Naming Rules
XML elements must follow these naming rules:
Names can contain letters, numbers, and other characters
Names cannot start with a number or punctuation character
Names cannot start with the letters xml (or XML, or Xml, etc)
Names cannot contain spaces
Any name can be used, no words are reserved.

Best Naming Practices
Make names descriptive: <first_name>, <last_name>.
Make names short and simple, like this: <book_title> not like this: <the_title_of_the_book>.
Avoid "-". If you name something "first-name," some software may think you want to subtract
name from first.
Avoid ".". If you name something "first.name," some software may think that "name" is a
property of the object "first."
Avoid ":". Colons are reserved to be used for something called namespaces (more later).
Non-English letters like are perfectly legal in XML, but watch out for problems if your
software doesn't support them.

Naming Styles
There are no naming styles defined for XML elements. But here are some commonly used:
Style Example Description
Lower case <firstname> All letters lower case
Upper case <FIRSTNAME> All letters upper case
Underscore <first_name> Underscore separates words
Pascal case <FirstName> Uppercase first letter in each word
Camel case <firstName> Uppercase first letter in each words exept the first
If you choose a naming style, it is good to be consistent!
XML documents often have a corresponding database. A good practice is to use the naming rules
of your database for the elements in the XML documents.

XML Elements are Extensible
XML elements can be extended to carry more information.
Look at the following XML example:
<note>
<to>Tove</to>
<from>Jani</from>
<body>Don't forget me this weekend!</body>
</note>
Let's imagine that we created an application that extracted the <to>, <from>, and <body>
elements from the XML document to produce this output:
MESSAGE
To: Tove
From: Jani
Don't forget me this weekend!
Imagine that the author of the XML document added some extra information to it:
<note>
<date>2008-01-10</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>


XML Attributes:
XML elements can have attributes, just like HTML.
Attributes provide additional information about an element.
XML Attributes
In HTML, attributes provide additional information about elements:
<img src="computer.gif">
<a href="demo.asp">
Attributes often provide information that is not a part of the data. In the example below, the file
type is irrelevant to the data, but can be important to the software that wants to manipulate the
element:
<file type="gif">computer.gif</file>


XML Attributes Must be Quoted
Attribute values must always be quoted. Either single or double quotes can be used. For a
person's sex, the person element can be written like this:
<person sex="female">
or like this:
<person sex='female'>
If the attribute value itself contains double quotes you can use single quotes, like in this example:
<gangster name='George "Shotgun" Ziegler'>
or you can use character entities:
<gangster name="George &quot;Shotgun&quot; Ziegler">


XML Elements vs. Attributes
Take a look at these examples:
<person sex="female">
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>

<person>
<sex>female</sex>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
In the first example sex is an attribute. In the last, sex is an element. Both examples provide the
same information.
There are no rules about when to use attributes or when to use elements. Attributes are handy in
HTML. In XML my advice is to avoid them. Use elements instead.

My Favorite Way
The following three XML documents contain exactly the same information:
A date attribute is used in the first example:
<note date="10/01/2008">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
A date element is used in the second example:
<note>
<date>10/01/2008</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
An expanded date element is used in the third: (THIS IS MY FAVORITE):
<note>
<date>
<day>10</day>
<month>01</month>
<year>2008</year>
</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>



XML DTD or Document Type Definition

DTD is expected to define formal grammar of XML based markup language(s).
Basically DTD contains list of elements that can occur in markup, list of attributes of each
element, possible attribute values or value types (may declare default attribute values too)
and content model that specifies allowed nesting of elements.
This information can be used in several ways.
1. One can use DTD to validate document, i.e., to check whether document follows formal rules
defined in DTD, in this way one can detect possible errors (like misspelled element names,
attribute names/values, wrongly nested elements etc.) that otherwise would be difficult to notice.

2. One can use DTD just to provide accurate description of markup language.

3. One can use DTD to define character entities, specify default attributes and bind elements to
XML namespaces.

Elements Type Declaration

Elements used in markup language are declared as follows

<!ELEMENT ElementName FormalContentModel>

where ElementName is name of element like h1, par, table, ul etc.
and FormalContentModel is expression that specifies its content model.
In XML DTD content model may specify what elements can be children of given elementand
whether element may contain character data.

There are several possible content models. They are described below.

1. EMPTY
This is the simplest content model that says that element is empty and should not contain any
character data or any nested elements.
For example XHTML 'br' element that is used for forced line breaks <br/> is empty element.

In DTD it is described as follows:

<!ELEMENT br EMPTY>

Usually empty elements are represented by empty tags like <br/> but <br></br> is also valid
markup.

2. ANY
Simple content model. It says that element may contain anything, including character data or any
other elements (that are declared in DTD).

3. Mixed
Mixed content model should be used when element may contain both character data and other
elements.

Content model looks like (#PCDATA | ChildName1 | ChildName2 | ... | ChildNameN)*
where ChildNames are names of possible child elements.
If no child elements are allowed this content model reduces to (#PCDATA)

Example:
Suppose that 'group' element may contain text, or 'subgroup' element and 'subgroup'
element may contain only text, no tags inside, like
<group>
My Group
<subgroup>First Subgroup</subgroup>
<subgroup>Second Subgroup</subgroup>
</group>

In DTD these elements can be described as:

<!ELEMENT group (#PCDATA | subgroup)*>
<!ELEMENT subgroup (#PCDATA)>

'Mixed' content model does not define order of child elements, does not specify how many times
child element may be repeated in markup, and can not be combined with other content models.

For example the following models are illegal:
(#PCDATA | em | strong | strong)*
<?warning repeated names are not allowed ?>
(#PCDATA | em | strong)+
<?warning '+' and '?' keys are not used in 'Mixed' content model ?>
(#PCDATA | (em | strong))*
<?warning In 'Mixed' content model choices should not be nested ?>



4. children
Unlike 'Mixed' content model, this one applies to elements that may contain only child elements
and should not contain any child text nodes. It may specify list of child elements, in addition it
may impose restrictions on their possible order or specify how many times certain element may
occur in content model.
This is achieved by combining sequences and choices.
Sequence is ordered list of child elements that looks like
(FirstChild, SecondChild, ThirdChild)
Choice is unordered list of child elements like
(Child | AnotherChild | YetAnotherChild)
Sequence and choice can be combined to describe more complex content models

Signs '?', '+' and '*' can be used to specify how many times content model may be repeated ('?'
means 1 or 0, '+' means > 0, '*' means any times)
they may appear after sequence or choice and after any element name inside sequence or choice.

Examples:

<!ELEMENT fraction (numerator, denominator)>
<?note Fraction has numerator followed by denominator ?>
<!ELEMENT list (ListItem)+>
<?note List contains at least one list item ?>
<!ELEMENT table (TableCaption?, TableRow+)>
<?note Table contains optional caption (it can be omitted) followed by at least one table
row ?>
<!ELEMENT matrix (MatrixRow, MatrixRow+)>
<?note matrix has at least two rows ?>
<!ELEMENT parent (FirstChild, (AnotherChild|YetAnotherChild)+, LastChild)>
<?note parent must contain FirstChild followed by one or more other children and
ended with LastChild ?>
<!ELEMENT shortList (item, item, item?, item?, item?, item?, item?, item?, item?)>
<?note shortList contains at least two and at most nine items ?>

DECLARING ATTRIBUTES

If element has some attributes they must be declared in DTD as follows

<!ATTLIST ElementName
AttributeName AttributeType DefaultDeclaration
AttributeName AttributeType DefaultDeclaration
AttributeName AttributeType DefaultDeclaration>

AttributeName is full (qualified) name of attribute like href, xml:lang, title. If elements has
more then one attribute list declarations then these lists are simply merged and if certain
attribute is declared several times then first declaration overwrites all subsequent ones.

AttributeType is either string type (CDATA) that means attribute value may be arbitrary,
tokenized type like ID, IDREF, IDREFS, NMTOKEN, NMTOKENS or enumerated type (list of
all possible attribute values).

DefaultDeclaration may specify whether attribute is required and if attribute is not required then
it may specify default attribute value.

STRING TYPE

String type (CDATA) imposes no restriction on attribute value, it may carry arbitrary character
data that does not break well-formedness of document.

TOKENIZED TYPES

Most important tokenized types are the following:

NMTOKEN. Attributes of this type must have values that consist from any letters (not
necessary Latin), digits or characters '_', '-', '.', ':'

Example:
<!ATTLIST span xml:lang NMTOKEN #IMPLIED>

NMTOKENS. The same as NMTOKEN or space separated list of NMTOKENs

Example:
<!ATTLIST span class NMTOKENS #IMPLIED>

ID. It is the same as NMTOKEN but first character should be letter, '_' or ':'
In addition ID type attribute values must be unique (two ID type attributes that appear in single
document are not allowed to carry the same value).

Example:
<!ATTLIST span id ID #IMPLIED>

IDREF. Must contain reference to unique ID (value of any ID type
attribute).

Example:
<!ATTLIST a nextfocus IDREF #IMPLIED>

IDREFS. Must contain reference to unique ID or space separated list
of such a references.

Example:
<!ATTLIST group related IDREFS #IMPLIED>

ENUMERATED TYPE

This type of attributes may have only limited number of predefined values.

Example:
<!ATTLIST pre xml:space (preserve) #IMPLIED>
<!ATTLIST txt xml:space (default|preserve) #IMPLIED>

DEFAULT ATTRIBUTE DECLARATION

There are several types of default declarations. Most important are:

#IMPLIED
Keyword #IMPLIED specifies that attribute can be omitted

#REQUIRED
Keyword #REQUIRED means that attribute value must be explicitly
specified in markup

Default
The same as #IMPLIED but if attribute is omitted
XML parser must attach attribute with default value
to element and pass it to application.

Example:
<!ATTLIST txt xml:space (default|preserve) "preserve">
<?note In this case <txt>Text</txt> will be treated as <txt
xml:space="preserve">Text</txt> ?>

#FIXED
The same as default but in this case default value
is the only possible attribute value.

Example:
<!ATTLIST root xmlns CDATA #FIXED "http://google.com/search?q=xml-maiden">

ATTRIBUTE VALUE NORMALIZATION

values of all attributes are normalized by XML parser. Basically it means that all tabs, carriage
returns and line feed characters are replaced with space, and if attribute is of tokenized type then
multiple spaces in attribute value are replaced by single space, while leading and trailing spaces
are stripped.

CHARACTER ENTITIES

Custom character entities can be defined as follows <!ENTITY EntityName EntityValue>
Further they can be referred in XML document as &EntityName;
They can be used to define convenient notations for frequently used constructions or difficult to
access characters. If some character entity is declared several times then first declaration
overwrites later ones.

Example:
<!ENTITY aacute "&#x00E1;">
<!ENTITY Aacute "&#x00C1;">

PARAMETER ENTITIES

Parameter entities can be used to introduce convenient notation for frequently used
constructions.
Parameter entity should be used within DTD (not in XML markup) they are declared as follows

<!ENTITY % EntityName EntityValue>
and further they can be referred in DTD as
%EntityName;

For example:
<!ENTITY % Attributes "attr NMTOKENS #IMPLIED xml:id ID #IMPLIED">
<!ATTLIST lf %Attributes;>
<!ATTLIST wr %Attributes;>
is equivalent to
<!ATTLIST lf attr NMTOKENS #IMPLIED xml:id ID #IMPLIED>
<!ATTLIST wr attr NMTOKENS #IMPLIED xml:id ID #IMPLIED>

If some parameter entity is declared several times then first declaration overwrites later ones.
Parameter entities may be stored in external DTDs.

In this case they can be declared as follows:

<!ENTITY % EntityName SYSTEM "http://mydomain.com/myentity.dtd">
OR
<!ENTITY % EntityName PUBLIC "Formal Public Identifier"
"http://mydomain.com/myentity.dtd">

CONDITIONAL SECTIONS

Conditional sections are used to include or ignore certain sections from DTD. They look like

<![INCLUDE[
<!ELEMENT title (#PCDATA)>
<?note This section is processed ?>
]]>
<![IGNORE[
<!ELEMENT caption (#PCDATA)>
<?note This section is ignored ?>
]]>

Usually they are combined with parameter entities as follows

<!ENTITY % condition "IGNORE">
<![%condition;[
<!ELEMENT title (#PCDATA)>
<? This section is ignored if value of parameter entity 'condition'
is "IGNORE" and included if "INCLUDE". One can redefine value of
parameter entities in any preceding DTD subset (incl. internal one) ?>
]]>

In this way one can reconfigure DTD by redefining certain parameter entities.

PROCESSING INSTRUCTIONS

Processing instructions look like <?Name content?>.They are used to pass certain information to
applications.

For example the following instruction, included in
XHTML 1.1 DTD, passes title of DTD to W3C markup validator
<?doc type="doctype" role="title" { XHTML 1.1 } ?>

INTERNAL AND EXTERNAL DTDS

Document Type Definition can be either internal, external or combination of these two. Internal
DTD is included in document's prolog before root element. It looks like

<!DOCTYPE RootElementName [ INTERNAL DTD IS PLACED HERE]>



External DTD is stored in separate dtd file served as application/xml-dtd and can be linked to
document, like

<!DOCTYPE RootElementName SYSTEM "http://mydomain.com/mydtd.dtd">

OR

<!DOCTYPE RootElementName PUBLIC "Formal Public Identifier"
"http://mydomain.com/mydtd.dtd">
internal and external DTDs can be combined

<!DOCTYPE RootElementName SYSTEM "http://mydomain.com/mydtd.dtd"
[INTERNAL DTD IS PLACED HERE]>
OR
<!DOCTYPE RootElementName PUBLIC "Formal Public Identifier"
"http://mydomain.com/mydtd.dtd" [INTERNAL DTD IS PLACED HERE]>

Note that XML parsers are NOT required to read external DTDs therefore information that
may influence rendering of XML document should be stored in internal DTD subset (basically
this applies to definitions of character entities and default attribute values).


























Summary for web technologies:


Most Web pages remote or local are a combination of those technologies
Raw content, placed inside
HTML tags,
Interactivity produced with the help of CSS rules
JavaScript and VB Script scripting languages
Newer technologies like DHTML, XHTML, and XML are also a part of dynamic web
development languages.

A little knowledge now can prepare you for new technologies and help you keep up in the web
development process

Das könnte Ihnen auch gefallen