0% found this document useful (0 votes)
305 views

Basics of Asp: Server Side Asp Code Using Vbscript

The document provides an overview of basic ASP concepts including: 1. ASP code uses VBScript by default and includes both server-side and client-side scripting capabilities. Server-side code runs on the web server while client-side code runs in the browser. 2. ASP supports common arithmetic, comparison, logical, and string operators similar to other programming languages. Variables are used to store and transfer information during script execution. 3. Variables must be declared before use and follow common naming conventions. Constants are similar but their values cannot change once declared. The document demonstrates various ASP coding examples including variables, operators, and conditional logic.

Uploaded by

LDSDude
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
305 views

Basics of Asp: Server Side Asp Code Using Vbscript

The document provides an overview of basic ASP concepts including: 1. ASP code uses VBScript by default and includes both server-side and client-side scripting capabilities. Server-side code runs on the web server while client-side code runs in the browser. 2. ASP supports common arithmetic, comparison, logical, and string operators similar to other programming languages. Variables are used to store and transfer information during script execution. 3. Variables must be declared before use and follow common naming conventions. Constants are similar but their values cannot change once declared. The document demonstrates various ASP coding examples including variables, operators, and conditional logic.

Uploaded by

LDSDude
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 17

Basics of ASP

Below we have a simple ASP script programmed in VBScript and includes the
necessary HTML as well. This is only server-side scripting.

Server Side ASP Code using VBScript:

<html>
<body>
<%
Dim myString
myString = Date()
Response.Write("The date is: " & myString)
%>
</body>
</html>

Display:

The date is: 7/3/2008

ASP Code w/ VBScript and Client Side Javascript Code:

<script>
document.write("The date is:<%
Dim myString
myString = Date()
Response.Write(myString)
%>")
</script>

Display:

The date is: 7/3/2008

ASP Operators

ASP is programmed in VBScript by default, thus ASP's operators are VBScript


operators by defaul

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.

Operator English Example Result


+ Addition myNum = 3 + 4 myNum = 7
- Subtraction myNum = 4 - 1 myNum = 3
* Multiplication myNum = 3 * 2 myNum = 6
/ Division myNum = 9 / 3 myNum = 3
^ Exponential myNum = 2 ^ 4 myNum = 16
Mod Modulus myNum = 23 Mod 10 myNum = 3
- Negation myNum = -10 myNum = -10
\ Integer Division myNum = 9 \ 3 myNum = 3

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.

Operator English Example Result


= Equal To 4=3 False
< Less Than 4<3 False
> Greater Than 4>3 True
<= Less Than Or Equal To 4 <= 3 False
>= Greater Than Or Equal To 4 >= 3 True
<> Not Equal To 4 <>3 True

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.

Operator English Example Result


And Both Must be TRUE True and False False
Or One Must be TRUE True or False True
Not Flips Truth Value Not True False

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

Operator English Example Result


& String Concatenation string4 = "Bob" & " runs" string4 = "Bob runs"

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.

All VBScript variable rules can be applied to your ASP code.

In ASP/VBScript, it is possible not to declare variables at all. A variable can appear in


the program, though it has never been declared. It is called default declaring.
However, such practice leads to errors and should be avoided.

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.

It can be mathematic constants, passwords, paths to files, etc.

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:

Const myConst = "myText"

'it is allowed to declare a few constants on the one line


Const PI = 3.14159, Wg = 2.78
Next example demonstrates the advantage of constants: during the calculations with
number PI, you can type in your code only constants names instead of typing this
number each time.

...

vCircle = PI * vRadius^2

Declaring a Variable in ASP


It is a good programming practice to declare all your variables before you use them,
even though it is not required.

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 Variable Naming Conventions

ASP uses VBScript by default and so it also uses VBScripts variable naming
conventions. These rules are:

1. Variable name must start with an alphabetic character (A through Z or a


through z). Variables must begin with a letter not a number or an underscore
2. Variables cannot contain a period
3. Variables cannot be longer than 255 characters (don't think that'll be a
problem!)
4. Variables must be unique in the scope in which it is declared (Basically, don't
declare the same variable name in one script and you will be OK).
5. Case sensitivity is not important in VBScript.
6. They cannot be a predefined identifier (such as dim, variable, if, etc.)

Examples:
<%@ LANGUAGE="VBSCRIPT" %>
<%
'Commented lines starting with an apostrophe are not executed in VBScript
'First we will declare a few variables.

Dim myText, myNum

'To declare a variable, you just put the word Dim in front of the variable name.
'Let's assign a value to these

myText = "Have a nice day!"


myNum = 5

'Note that myText is a string and myNum is numeric.

'Next we will display these to the user.


Response.Write(myText)
'To concatenate strings in VBScript, use the ampersand
Response.Write(" My favourite number is " & myNum)
%>

Output: Have a nice day! My favourite number is 5.

<html>
<body>
<%
dim name
name="Donald Duck"
response.write("My name is: " & name)
%>
</body>
</html>

Output: My name is: Donald Duck

Time-based greeting using VBScript

<html>
<body>
<%
dim h
h=hour(now())

response.write("<p>" & now())


response.write("</p>")
If h<12 then
response.write("Good Morning!")
else
response.write("Good day!")
end if
%>
</body>
</html>

Output:

7/3/2008 2:24:37 PM

Good day!

Time-based greeting using JavaScript


<%@ language="javascript" %>
<html>
<body>
<%
var d=new Date()
var h=d.getHours()
Response.Write("<p>")
Response.Write(d)
Response.Write("</p>")
if (h<12)
{
Response.Write("Good Morning!")
}
else
{
Response.Write("Good day!")
}
%>
</body>
</html>

Output:

Thu Jul 3 14:24:37 EDT 2008

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:

myNum = 25 myString = Hello


myGarbage = I changed my variable

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)

You then have access to:

Oceans(0) = 'Indian'
Oceans(1) = 'Pacific'
Oceans(2) = 'Atlantic
...

And so on. You always begin with spot "0".


You can create an array of specific size or you can create a dynamic sized array.
Below we have examples of both types of arrays.

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:

• The name of the array


• The value you want to store
• The position in the array where you want to store the value.

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"

This example demonstrates how to declare an array that stores names.

<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

The Global.asa file is an optional file that can contain declarations of objects,
variables, and methods that can be accessed by every page in an ASP application. All
valid browser scripts (JavaScript, VBScript, JScript, PerlScript, etc.) can be used
within Global.asa.

The Global.asa file can contain only the following:

• Application events
• Session events
• <object> declarations
• TypeLibrary declarations
• the #include directive

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

In Global.asa you can tell the application and session objects what to do when the
application/session starts and what to do when the application/session ends. The
code for this is placed in event handlers. The Global.asa file can contain four types of
events:

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.

A Global.asa file could look something like this:

<script language="vbscript" runat="server">


sub Application_OnStart
'some code
end sub
sub Application_OnEnd
'some code
end sub
sub Session_OnStart
'some code
end sub
sub Session_OnEnd
'some code
end sub
</script>

The Global.asa file:

<script language="vbscript" runat="server">


Sub Application_OnStart
Application("visitors")=0
End Sub
Sub Session_OnStart
Application.Lock
Application("visitors")=Application("visitors")+1
Application.UnLock
End Sub
Sub Session_OnEnd
Application.Lock
Application("visitors")=Application("visitors")-1
Application.UnLock
End Sub
</script>

To display the number of current visitors in an ASP file:

<html>
<head>
</head>
<body>
<p>
There are <%response.write(Application("visitors"))%>
online now!
</p>
</body>
</html>

The #include Directive

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.

How to Use the #include Directive

Here is a file called "mypage.asp":

<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>

Here is the "wisdom.inc" file:

"One should never increase, beyond what is necessary,


the number of entities required to explain anything."

Here is the "time.inc" file:

<%
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>

Syntax for Including Files

To include a file in an ASP page, place the #include directive inside comment tags:

<!--#include virtual="somefilename"-->
or
<!--#include file ="somefilename"-->

ASP Session Variables

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:

You visited this site at: 11:31:09 PM

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
%>

ASP Session Timeout

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:

The timeout is: 240

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 assign it, and then

if Session("age") >= 21 ...

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

to completely end that session's run.

ASP Procedures

In ASP you can call a JavaScript procedure from a VBScript and vice versa.

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.

You might also like