Basics of Asp: Server Side Asp Code Using Vbscript
Basics of Asp: Server Side Asp Code Using Vbscript
Below we have a simple ASP script programmed in VBScript and includes the
necessary HTML as well. This is only server-side scripting.
<html>
<body>
<%
Dim myString
myString = Date()
Response.Write("The date is: " & myString)
%>
</body>
</html>
Display:
<script>
document.write("The date is:<%
Dim myString
myString = Date()
Response.Write(myString)
%>")
</script>
Display:
ASP Operators
Operators in ASP fall into four categories Math (arithmetic), Comparisons, the
somewhat more advanced Logic operators, and Leftovers(those that don't fit well
into any category).
The mathematical operators in ASP are similar to many other programming
languages. However, ASP does not support shortcut operators like ++, --, +=, etc.
Comparison Operators
Comparison operators are used when you want to compare two values to make a
decision. Comparison operators are most commonly used in conjunction with
"If...Then" and "While something is true do this..." statements, otherwise known as
conditional statements. The items that are most often compared are numbers. The
result of a comparison operator is either TRUE or FALSE.
Logical Operators
The above comparison operators result in a truth value of TRUE or FALSE. A logical
operator is used for complex statements that must make decisions based on one or
more of these truth values.
String Operators
The only string operator is the string concatenation operator "&" that takes two
strings and slams them together to form a new string. An example would be string1
= "Tim" and string2 = " is a Hero". The following code would combine these two
strings into one: string3 = string1 & string2
Variables
Variables provide temporary storage for information that will be needed during the
lifespan of the computer program (or application).
Variables are also used in programming to transfer information from one part of the
program to another
ASP Variables
A variable is used to store information.
If the variable is declared outside a procedure it can be changed by any script in the
ASP file. If the variable is declared inside a procedure, it is created and destroyed
every time the procedure is executed.
To program ASP you actually need to know the VBScript scripting language.
ASP: Constants
Constants just as variables are used to store information.
The main difference between constants and variables is that constant value can not
be changed in the process of running program. If we attempt to re-assign the value
of the constant we'll get a run time error.
By using a constant you "lock in" the value which prevents you from accidentally
changing it.
To declare a constant in VBScript we use the Const keyword. Have a look at the
following example:
...
vCircle = PI * vRadius^2
In ASP you declare a variable with the use of the Dim keyword, which is short for
Dimension.
Dimension in English refers to the amount of space something takes up in the real
world, but in computer terms it refers to space in computer memory.
Variables can be declared one at a time or all at once. Below is an example of both
methods.
The variable value will be kept in memory for the life span of the current page and
will be released from memory when the page has finished executing.
To declare variables accessible to more than one ASP file, declare them as session
variables or application variables.
Whatever you do, be descriptive and reasonably lengthed. Don't go for variables like
"i" and "j", those drive you crazy when you're trying to debug later. And don't go for
variables like "lastnameofprimarycontact" - that makes it nearly impossible to read
through the code.
So let’s say you name your variables short but meaningful names - names like
SiteName or UserName or SiteID.
For a regular variable, you simply assign a value to it. You don't have to predefine it -
it knows by what type of variable you're assigning to it what sort of a variable it is.
So if you say:
SiteName = "ASP"
it knows it's a text variable that you can do text operations on. If you say
BooksOrdered = 13
then it knows it's a numeric variable and that you can do addition and subtraction to
it.
The date subtype needs a special format so that the system doesn't think it's just a
string or a division problem :). You use # signs to indicate it's a date, as in:
DateStarted = #01/15/2001#
Also, if you want to use booleans (true/false), you simply use TRUE or FALSE as your
values. So:
FinishedTask = TRUE
ASP Code:
<%
'Single Variable Declarations
Dim myVar1
Dim myVar2
'Multiple Variable Declarations
Dim myVar6, myVar7, myVar8
%>
ASP uses VBScript by default and so it also uses VBScripts variable naming
conventions. These rules are:
Examples:
<%@ LANGUAGE="VBSCRIPT" %>
<%
'Commented lines starting with an apostrophe are not executed in VBScript
'First we will declare a few variables.
'To declare a variable, you just put the word Dim in front of the variable name.
'Let's assign a value to these
<html>
<body>
<%
dim name
name="Donald Duck"
response.write("My name is: " & name)
%>
</body>
</html>
<html>
<body>
<%
dim h
h=hour(now())
Output:
7/3/2008 2:24:37 PM
Good day!
Output:
Good day!
<html>
<body>
<%
dim i
for i=1 to 6
response.write("<h" & i & ">Header " & i & "</h" & i & ">")
next
%>
</body>
</html>
Output:
Header 1
Header 2
Header 3
Header 4
Header 5
Header 6
ASP - Assigning Values to ASP Variables
Assigning values in ASP is straightforward enough, just use the equals "=" operator.
Below we have set a variable equal to a number and a separate variable equal to a
string.
ASP Code:
<%
'Single Variable Declarations
Dim myString, myNum, myGarbage
myNum = 25
myString = "Hello"
myGarbage = 99
myGarbage = "I changed my variable"
Response.Write("myNum = " & myNum & "<br />")
Response.Write("myString = " & myString & "<br />")
Response.Write("myGarbage = " & myGarbage & "<br />")
%>
Output:
Declare an array
Arrays are used to store a series of related data items.
Arrays can help you 'group' sets of information together, like the names of states, or
names of countries, or colors, or any other grouping.
An array is a variable that has multiple 'buckets' associated with it. Instead of
creating variables called Book1, Book2, Book3, Book4, Book5, and so on, you simply
make one array:
Dim Book(20)
First off all, note that arrays start with *0* and not with *1*. So if you use:
Dim Oceans(6)
Oceans(0) = 'Indian'
Oceans(1) = 'Pacific'
Oceans(2) = 'Atlantic
...
ASP Code:
<%
Dim myFixedArray(3) 'Fixed size array
Dim myDynArray() 'Dynamic size array
%>
Our fixed array is going to store the names of famous people. To assign a value to an
array you need to know three things:
An array is a group of variables that you can access by specifying the position inside
the array. Our array myFixedArray has four positions: 0, 1, 2 and 3. Let's assign
some values to our array.
ASP Code:
<%
Dim myFixedArray(3) 'Fixed size array
myFixedArray(0) = "Albert Einstein"
myFixedArray(1) = "Mother Teresa"
myFixedArray(2) = "Bill Gates"
myFixedArray(3) = "Martin Luther King Jr."
%>
Dynamic Arrays:
To create an array whose size can be changed at any time simply do not put a
number within the parenthesis when you declare the array. When you know what
size you want the array to be use the ReDim keyword. You may ReDim as many
times as you wish.
If you want to keep your data that already exists in the array then use the Preserve
keyword. Below is an example of all these things we have just talked about.
ASP Code:
<%
Dim myDynArray() 'Dynamic size array
ReDim myDynArray(1)
myDynArray(0) = "Albert Einstein"
myDynArray(1) = "Mother Teresa"
ReDim Preserve myDynArray(3)
myDynArray(2) = "Bill Gates"
myDynArray(3) = "Martin Luther King Jr."
For Each item In myDynArray
Response.Write(item & "<br />")
Next
%>
Display:
Albert Einstein Mother Teresa Bill Gates Martin Luther King Jr.
You can have two dimensions, or up to 60 dimensions. Why would you want this?
Well, let's take our chessboard example. Say you wanted an array location to
indicate each spot on a chessboard, so you could track pieces moving from one spot
to another. You could do:
Dim ChessSquares(64)
But then every time a piece moved you'd have to figure out where in that '64' it
belonged. This could get tricky. What if instead you said:
Dim ChessSquares(8,8)
Now it's easy! Now you simply number the rows of the board from 1-8, and the
columns of the board from 1-8, and change each number separately. If a Black Pawn
moved from row 2, column 4 to row 3, column 4, you could say:
ChessSquares(2,4) = "EMPTY"
ChessSquares(3,4) = "BP"
<html>
<body>
<%
Dim famname(5),i
famname(0) = "Jan Egil"
famname(1) = "Tove"
famname(2) = "Hege"
famname(3) = "Stale"
famname(4) = "Kai Jim"
famname(5) = "Borge"
For i = 0 to 5
response.write(famname(i) & "<br />")
Next
%>
</body>
</html>
Output:
Jan Egil
Tove
Hege
Stale
Kai Jim
Borge
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 a specific application.
The Global.asa file is an optional file that can contain declarations of objects,
variables, and methods that can be accessed by every page in an ASP application. All
valid browser scripts (JavaScript, VBScript, JScript, PerlScript, etc.) can be used
within Global.asa.
• Application events
• Session events
• <object> declarations
• TypeLibrary declarations
• the #include directive
Note: The Global.asa file must be stored in the root directory of the ASP application,
and each application can only have one Global.asa file.
Events in Global.asa
In Global.asa you can tell the application and session objects what to do when the
application/session starts and what to do when the application/session ends. The
code for this is placed in event handlers. The Global.asa file can contain four types of
events:
Application_OnStart - This event occurs when the FIRST user calls the first page
from an ASP application. This event occurs after the Web server is restarted or after
the Global.asa file is edited. The "Session_OnStart" event occurs immediately after
this event.
Session_OnStart - This event occurs EVERY time a NEW user requests his or her
first page in the ASP application.
Session_OnEnd - This event occurs EVERY time a user ends a session. A user ends
a session after a page has not been requested by the user for a specified time (by
default this is 20 minutes).
Application_OnEnd - This event occurs after the LAST user has ended the session.
Typically, this event occurs when a Web server stops. This procedure is used to clean
up settings after the Application stops, like delete records or write information to text
files.
<html>
<head>
</head>
<body>
<p>
There are <%response.write(Application("visitors"))%>
online now!
</p>
</body>
</html>
You can insert the content of one ASP file into another ASP file before the server
executes it, with the #include directive. The #include directive is used to create
functions, headers, footers, or elements that will be reused on multiple pages.
<html>
<body>
<h3>Words of Wisdom:</h3>
<p><!--#include file="wisdom.inc"--></p>
<h3>The time is:</h3>
<p><!--#include file="time.inc"--></p>
</body>
</html>
<%
Response.Write(Time)
%>
If you look at the source code in a browser, it will look something like this:
<html>
<body>
<h3>Words of Wisdom:</h3>
<p>"One should never increase, beyond what is necessary,
the number of entities required to explain anything."</p>
<h3>The time is:</h3>
<p>11:33:42 AM</p>
</body>
</html>
To include a file in an ASP page, place the #include directive inside comment tags:
<!--#include virtual="somefilename"-->
or
<!--#include file ="somefilename"-->
To store a Session Variable you must put it into the Contents collection, which is very
easy to do. If you have already read the ASP Arrays Lesson then this bit of code will
be a cinch!
Here we are saving the Time when someone visited this page into the Session
Contents collection and then displaying it .
ASP Code:
<%
'Start the session and store information
Session("TimeVisited") = Time()
Response.Write("You visited this site at: " & Session("TimeVisited"))
%>
Display:
Here we are creating two things actually: a key and a value. Above we created the
key "TimeVisited" which we assigned the value returned by the Time() function.
Whenever you create a Session Variable to be stored in the Session Contents
collection you will need to make this Key / Value pair.
ASP Session ID
The ASP Session ID is the unique identifier that is automatically created when a
Session starts for a given visitor. The Session ID is a property of the Session Object
and is rightly called the SessionID property. Below we store the user's SessionID into
a variable.
ASP Code:
<%
Dim mySessionID
mySessionID = Session.SessionID
%>
A Session will not last forever, so eventually the data stored within the Session will
be lost. There are many reasons for a Session being destroyed. The user could close
their browser or they could leave their computer for an extended amount of time and
the Session would time out. You can set how long it takes, in minutes, for a session
to time out with the Timeout property.
Below we set our session to timeout after 240 minutes, which should be more than
enough time for most web sites.
ASP Code:
<%
Session.Timeout = 240
Response.Write("The timeout is: " & Session.Timeout)
%>
Display:
Usually when you code an ASP script, the variables you use only exist while the script
runs. But what if you want to code a shopping cart, or something else where data is
kept active?
You could start storing all the data in a database, but this takes up space and uses
time. It's much easier to work with the session variable space. By default, this space
stays active for a given user for 20 minutes.
The session begins as soon as a given computer has a session value stored for them.
This creates a cookie for that computer, logging the date and time of entry. From
that point forward, every new session value change they do updates the 20 minute
timer. If you want to change the timeout value, use:
Session.Timeout=10
or whatever minute number you want to use. Remember, session values take up
memory. So you want this to be long enough that the user can get through their
task, but short enough that you do not have many different sessions open without
reason.
To use a session variable, simply put data into it. If a user enters their age and you
want to track this for as long as the user is using your pages (to keep them away
from mature material, for example) you would use:
Session("age") = 25
to work with it. Typical uses for the session variable are an age, a log-in user ID and
password, shopping items in a shopping cart, and flash vs html user preferences.
If you're done with a given session and want to end it early, perhaps because the
user chose a "log off" option on your site, you would use
Session.Abandon
ASP Procedures
In ASP you can call a JavaScript procedure from a VBScript and vice versa.