Asp Tutorial
Asp Tutorial
What is ASP?
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
The Option Pack can be downloaded from Microsoft
PWS is a smaller - but fully functional - version of IIS
PWS can be found on your Windows 95/98 CD
ASP Compatibility
To run IIS you must have Windows NT 4.0 or later
To run PWS you must have Windows 95 or later
ChiliASP is a technology that runs ASP without Windows OS
InstantASP is another technology that runs ASP without Windows
Note: Look for the IIS (or PWS) symbol in your start menu or task bar. The program has functions for
starting and stopping the web server, disable and enable ASP, and much more.
In our ASP tutorial, every example shows the hidden ASP source code. This will make it easier for you to
understand how it works.
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.
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:
Example
<!DOCTYPE html>
<html>
<body>
<%
response.write("Hello World!")
%>
</body>
</html>
There is also a shorthand method for the response.write command. The following example also sends
the text "Hello World" to the browser:
Example
<!DOCTYPE html>
<html>
<body>
<%
="Hello World!"
%>
</body>
</html>
You can use several scripting languages in ASP. However, the default scripting language is VBScript:
<!DOCTYPE html>
<html>
<body>
<%
response.write("Hello World!")
%>
</body>
</html>
The example above writes "Hello World!" into the body of the document.
Declare a variable
Variables are used to store information. This example demonstrates how to declare a variable, assign a
value to it, and use the value in a text.
Declare an array
Arrays are used to store a series of related data items. This example demonstrates how to declare an
array that stores names.
Lifetime of Variables
A variable declared outside a procedure can be accessed and changed by any script in the ASP file.
A variable declared inside a procedure is created and destroyed every time the procedure is executed.
No scripts outside the procedure can access or change the variable.
To declare variables accessible to more than one ASP file, declare them as session variables or
application variables.
Session Variables
Session variables are used to store information about ONE single user, and are available to all pages in
one application. Typically information stored in session variables are name, id, and preferences.
Application Variables
Application variables are also available to all pages in one application. Application variables are used to
store information about ALL users in one specific application.
In ASP you can call a JavaScript procedure from a VBScript and vice versa.
Procedures
The ASP source code can contain procedures and functions:
Example
<!DOCTYPE html>
<html>
<head>
<%
sub vbproc(num1,num2)
response.write(num1*num2)
end sub
%>
</head>
<body>
</body>
</html>
Insert the <%@ language="language" %> line above the <html> tag to write the procedure/function in
another scripting language:
Example
<%@ language="javascript" %>
<!DOCTYPE html>
<html>
<head>
<%
function jsproc(num1,num2)
{
Response.Write(num1*num2)
}
%>
</head>
<body>
<p>Result: <%jsproc(3,4)%></p>
</body>
</html>
Differences Between VBScript and JavaScript
When calling a VBScript or a JavaScript procedure from an ASP file written in VBScript, you can use the
"call" keyword followed by the procedure name. If a procedure requires parameters, the parameter list
must be enclosed in parentheses when using the "call" keyword. If you omit the "call" keyword, the
parameter list must not be enclosed in parentheses. If the procedure has no parameters, the
parentheses are optional.
When calling a JavaScript or a VBScript procedure from an ASP file written in JavaScript, always use
parentheses after the procedure name.
More Examples
Call procedures using VBScript
How to call both a JavaScript procedure and a VBScript procedure in an ASP file.
ASP Source:
<!DOCTYPE html>
<html>
<head>
<%
sub vbproc(num1,num2)
Response.Write(num1*num2)
end sub
%>
<script language="javascript" runat="server">
function jsproc(num1,num2)
{
Response.Write(num1*num2)
}
</script>
</head>
<body>
<p>Result: <%call vbproc(3,4)%></p>
<p>Result: <%call jsproc(3,4)%></p>
</body>
</html>
Output Result:
Result: 12
Result: 12
The Request.QueryString and Request.Form commands are used to retrieve user input from forms.
ASP Source:
<!DOCTYPE html>
<html>
<body>
<form action="demo_reqquery.asp" method="get">
Your name: <input type="text" name="fname" size="20" />
<input type="submit" value="Submit" />
</form>
<%
dim fname
fname=Request.QueryString("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!<br>")
Response.Write("How are you today?")
End If
%>
</body>
</html>
Output Result:
Your name:
ASP Source:
<!DOCTYPE html>
<html>
<body>
<form action="demo_simpleform.asp" method="post">
Your name: <input type="text" name="fname" size="20" />
<input type="submit" value="Submit" />
</form>
<%
dim fname
fname=Request.Form("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!<br>")
Response.Write("How are you today?")
End If
%>
</body>
</html>
Output Result:
Your name:
User Input
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>
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
Form Validation
User input should be validated on the browser whenever possible (by client scripts). Browser validation
is faster and reduces the server load.
You should consider server validation if the user input will be inserted into a database. A good way to
validate a form on the server is to post the form to itself, instead of jumping to a different page. The
user will then get the error messages on the same page as the form. This makes it easier to discover the
error.
Welcome cookie
How to create a Welcome cookie.
ASP Source:
<%
dim numvisits
response.cookies("NumVisits").Expires=date+365
numvisits=request.cookies("NumVisits")
if numvisits="" then
response.cookies("NumVisits")=1
response.write("Welcome! This is the first time you are visiting this Web page.")
else
response.cookies("NumVisits")=numvisits+1
response.write("You have visited this ")
response.write("Web page " & numvisits)
if numvisits=1 then
response.write " time before!"
else
response.write " times before!"
end if
end if
%>
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Output Result:
Welcome! This is the first time you are visiting this Web page.
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's
computer. Each time the same computer requests a page with a browser, it will send the cookie too.
With ASP, you can both create and retrieve cookie values.
It is also possible to assign properties to a cookie, like setting a date when the cookie should expire:
<%
Response.Cookies("firstname")="Alex"
Response.Cookies("firstname").Expires=#May 10,2012#
%>
How to Retrieve a Cookie Value?
The "Request.Cookies" command is used to retrieve a cookie value.
In the example below, we retrieve the value of the cookie named "firstname" and display it on a page:
<%
fname=Request.Cookies("firstname")
response.write("Firstname=" & fname)
%>
Output: Firstname=Alex
<%
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>
<%
Response.Cookies("firstname")="Alex"
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>
Assume that your server has sent all the cookies above to a user.
Now we want to read all the cookies sent to a user. The example below shows how to do it (note that
the code below checks if a cookie has Keys with the HasKeys property):
<!DOCTYPE html>
<html>
<body>
<%
dim x,y
for each x in Request.Cookies
response.write("<p>")
if Request.Cookies(x).HasKeys then
for each y in Request.Cookies(x)
response.write(x & ":" & y & "=" & Request.Cookies(x)(y))
response.write("<br />")
next
else
Response.Write(x & "=" & Request.Cookies(x) & "<br />")
end if
response.write "</p>"
next
%>
</body>
</html>
Output:
firstname=Alex
user:firstname=John
user:lastname=Smith
user:country=Norway
user:age=25
2. Use a form
You can use a form. The form passes the user input to "welcome.asp" when the user clicks on the
Submit button:
<form method="post" action="welcome.asp">
First Name: <input type="text" name="fname" value="" />
Last Name: <input type="text" name="lname" value="" />
<input type="submit" value="Submit" />
</form>
<%
fname=Request.form("fname")
lname=Request.form("lname")
response.write("<p>Hello " & fname & " " & lname & "!</p>")
response.write("<p>Welcome to my Web site!</p>")
%>
A Session object stores information about, or change settings for a user session.
<%
Session.Timeout=5
%>
<%
Session.Abandon
%>
Note: The main problem with sessions is WHEN they should end. We do not know if the user's last
request was the final one or not. So we do not know how long we should keep the session "alive".
Waiting too long for an idle session uses up resources on the server, but if the session is deleted too
soon the user has to start all over again because the server has deleted all the information. Finding the
right timeout interval can be difficult!
Tip: Only store SMALL amounts of data in session variables!
<%
Session("username")="Donald Duck"
Session("age")=50
%>
When the value is stored in a session variable it can be reached from ANY page in the ASP application:
Welcome <%Response.Write(Session("username"))%>
The line above returns: "Welcome Donald Duck".
You can also store user preferences in the Session object, and then access that preference to choose
what page to return to the user.
The example below specifies a text-only version of the page if the user has a low screen resolution:
<%If Session("screenres")="low" Then%>
This is the text version of the page
<%Else%>
This is the multimedia version of the page
<%End If%>
username
age
If you do not know the number of items in the Contents collection, you can use the Count property:
<%
dim i
dim j
j=Session.Contents.Count
Response.Write("Session variables: " & j)
For i=1 to j
Response.Write(Session.Contents(i) & "<br />")
Next
%>
Result:
Session variables: 2
Donald Duck
50
A group of ASP files that work together to perform some purpose is called an application.
Application Object
An application on the Web may consist of several ASP files that work together to perform some purpose.
The Application object is used to tie these files together.
The Application object is used to store and access variables from any page, just like the Session object.
The difference is that ALL users share ONE Application object (with Sessions there is ONE Session object
for EACH user).
The Application object holds information that will be used by many pages in the application (like
database connection information). The information can be accessed from any page. The information can
also be changed in one place, and the changes will automatically be reflected on all pages.
Store and Retrieve Application Variables
Application variables can be accessed and changed by any page in an application.
You can create Application variables in "Global.asa" like this:
In the example above we have created two Application variables: "vartime" and "users".
You can access the value of an Application variable like this:
There are
<%
Response.Write(Application("users"))
%>
active connections.
<%
dim i
For Each i in Application.Contents
Response.Write(i & "<br />")
Next
%>
If you do not know the number of items in the Contents collection, you can use the Count property:
<%
dim i
dim j
j=Application.Contents.Count
For i=1 to j
Response.Write(Application.Contents(i) & "<br />")
Next
%>
Loop Through the StaticObjects Collection
You can loop through the StaticObjects collection, to see the values of all objects stored in the
Application object:
<%
dim i
For Each i in Application.StaticObjects
Response.Write(i & "<br />")
Next
%>
<%
Application.Lock
'do some application object operations
Application.Unlock
%>