ASP

Lesson Plan

Section One: General Overview
Lesson 01 A General Overview
Lesson 02 Escape Characters
Lesson 03 The new String( ) Constructor
Lesson 04 Using VBScript with JavaScript
Lesson 05 Bringing It Together

Section Two: Request and Response
Lesson 06 The Response Methods
Lesson 07 The Response Properties
Lesson 08 The Request Collections and Misc.
Lesson 09 Response.Cookies and Request.Cookies

Section Three: Session, Application, and Includes
Lesson 10 Global ASA
Lesson 11 Application Object
Lesson 12 Session Object
Lesson 13 Include Files

Section Four: Server and ASPError
Lesson 14 Server Object
Lesson 15 ASPError Object

Section Five: Databases (and form field validation)
Lesson 16 Making A Connection
Lesson 17 Using A Recordset
Lesson 18 More About Recordsets
Lesson 19 Adding and Updating
Lesson 20 A Word About Date/Time

Lesson 01 A General Overview

A General Overview

Before We Start:

ASP stands for Active Server Pages. ASP comes from Microsoft and it promises a language neutral platform on which to develop dynamic web pages.

Your Scripts are written as plain text and stored in files with the .asp extension. When called upon, your script goes through the ASP script engine, which combines your scripts with information from the web surfer, possibly a database, and other sources as you see appropriate.

Based on the presumptions laid out on the home page, I assume you already know how to create text files with an .asp extension. I also assume you already know how to place your files into a virtual folder. There is a lot of documentation on how to do these things, but the subject matter is beyond the scope of this web site.

Get Started:

The best way to get into this lesson is simply to dive right into the script.

Below is the ASP Script for Lesson 01.

<%@LANGUAGE="JavaScript"%>

<%

Response.Write("<HTML>")

Response.Write("<BODY>")

Response.Write("Hello World<BR>")

Response.Write("</BODY>")

Response.Write("</HTML>")

%>

Click Here to run the script in a new window.

Tags:

This is a pretty simple example. My bet is that you already get it. Have you noticed that ASP tags are similar to HTML tags? There is a difference. <%ASP Goes Here.%> The ASP tags use a percent sign.

@LANGUAGE:

The @LANGUAGE attribute is set to "JavaScript". That means ASP will run our scripts through the JavaScript (JScript) script engine.

Most servers are set by default to use VBScript. We can change the default language for a single page by using the @LANGUAGE attribute. @LANGUAGE must be set BEFORE any other ASP commands. So, it's a good idea to put @LANGUAGE right at the very top, even before your HTML headers. @LANGUAGE can only be set ONCE in any particular script. It should also stand alone; don't put any other command inside the same set of tags.

Misc. Notes:

Response is an ASP object (Not to be confused with JavaScript objects) and Write is an ASP method (not to be confused with JavaScript methods). Response gets its own lesson later on.

The last thing we need to notice on this script is the difference between the ASP script and the resulting HTML Script.

Below is the HTML source code as seen on the client side.

<HTML<BODY>Hello World<BR</BODY</HTML>

The Client Side output is all on one line. If you haven't already, click the link to run the script and then View Source Code. You will see that the entire HTML text is one unbroken line. That's bad. On lager pages, it will make the HTML output difficult to read. Trust me; you can't find bugs if you can't even make heads or tails of what you're putting out to the client.

In Lesson 02 we will fix that problem.

Lesson 02 Escape Characters

Escape Characters

Not Out of Place:

The instruction of Escape Characters in Lesson 02 seems out of place. But it's not. Escape Characters are an integral part of using JavaScript in ASP. Lesson 02 is exactly the right spot for escape characters. Without escape characters, you will struggle to write effective ASP scripts in JavaScript. Sorry.

Get Started:

Below is the ASP Script for Lesson 02.

<%@LANGUAGE="JavaScript"%>

<%

Response.Write("<HTML>\r")

Response.Write("<FONT COLOR=\"red\">\"Hello World\"</FONT<BR>\r")

Response.Write("<FONT COLOR='blue'>'Hello World'</FONT<BR>\r")

Response.Write("</HTML>\r")

%>

Click Here to run the script in a new window.

Remember in Lesson 01 how the entire HTML output was on one line. The escape characters allow us to add carriage returns.

Below is the HTML source code as seen on the client side.

<HTML>

<FONT COLOR="red">"Hello World"</FONT<BR>

<FONT COLOR='blue'>'Hello World'</FONT<BR>

</HTML>

Escape Return:

I've reprinted a single line of ASP script below. Look at the "\r" at the end of the line.

Response.Write("<FONT COLOR=\"red\">\"Hello World\"</FONT<BR>\r")

The "\r" is a special character representing a carriage return. It's how I got the separate lines of HTML output on ...well... separate lines. That's vitally important on larger applications and larger pages. I said it before, but I'll say it again. Trust me; you can't find bugs if you can't even make heads or tails of what you're putting out to the client.

Escape Quote:

There's something else you should notice. See how I put the backslash underneath some of the quotation marks. What would happen if I remove the backslashes? Let's try the following line of code.

Response.Write("<FONT COLOR="red">"Hello World"</FONT<BR>")

I would get an error code, which is copied below.

Microsoft JScript compilation error '800a03ee'

Expected ')'

/asp/Section01/Script02.asp, line 4

Response.Write("<FONT COLOR="red">"Hello World"</FONT<BR>")

------^

No Escape:

What if I don't like Escape Characters? Do I have to use them?

You can limp along without them. Consider the line below.

Response.Write("<FONT COLOR='blue'>'Hello World'</FONT<BR>")

\b / Backspace
\cD / Control-D
\f / Form Feed
\n / New Line
\r / Carriage Return
\t / Tab
\xnn / Hexadecimal
\0nn / ASCII Escape Characters
\' / Single Quote
\" / Double Quote
\\ / Backslash

You can interchange single quotes with double quotes. It's awkward, in my opinion. But it works. Even with that said, HTML aesthetics are the least important reason to use Escape Characters.

The List:

A far more important reason to utilize escape characters is that it allows us to output a whole list of special characters.

Most Important:

But the most important reason to use Escape Characters (at least for any sophisticated application) is for your database connection. (Database connections get their own lesson later on.) Compare the two Connection Strings below.

var Connection="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Server.MapPath("\\TopLevelVirtualFolder") + "\\database\\myDatabase.mdb;"

Dim Connection;
Connection="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Server.MapPath("\TopLevelVirtualFolder") & "\database\myDatabase.mdb;"

Next Up:

There's another little tool we absolutely must have to write ASP JavaScript. And that's in lesson 03.

lesson03.aspThe new String( ) constructor

Get Started:

new String( ) is another strange place to go early on the lesson plan. But just like Escape Characters, new String ( ) is vital to successful ASP JavaScript applications. Below are two scripts for Lesson 03.

<%@LANGUAGE="JavaScript"%>

<%

//No ASP Here, just a regular HTML Page

%>

<HTML>

<STRONG>Type something into the text box and submit it.</STRONG>

<FORM ACTION="script03a.asp" METHOD="Post">

<INPUT TYPE="Text" NAME="WebPageVariable"<BR>

<STRONG>How Much Money do you make each month?</STRONG<BR>

<SELECT NAME="monthlySalary">

<OPTION>Under $5,000,000</OPTION>

<OPTION>Above $5,000,000</OPTION>

<OPTION>Nobody's darn business</OPTION>

</SELECT<BR>

<INPUT TYPE="Submit" VALUE="Submit">

</FORM>

</HTML>

Click Here to run the script in a new window.

Below is the actual ASP Script that does the heavy lifting.

<%@LANGUAGE="JavaScript"%>

<%

var WebPageVariable = new String( Request.Form("WebPageVariable") )

WebPageVariable = WebPageVariable.toUpperCase();

var monthlySalary = new String( Request.Form("monthlySalary") )

monthlySalary = monthlySalary.toLowerCase();

Response.Write("<HTML>\r");

Response.Write("The Web Page Variable you typed is: ");

Response.Write(WebPageVariable + "<BR>\r");

Response.Write("The monthly salary you listed is: " + monthlySalary + "<BR>\r");

Response.Write("</HTML>\r");

%>

new String( ) in Action:

Now check out the ASP lines below.

var monthlySalary = new String( Request.Form("monthlySalary") )

monthlySalary = monthlySalary.toLowerCase();

Request.Form gets its own lesson later on. Here's the point of showing it to you now. The data held in Request.Form (which ultimately comes from the user) is not a JavaScript data type. Instead, it is a native ASP data type. JavaScript cannot manipulate ASP data types.

The solution is cast the ASP data type into a JavaScript data type. In this case, the way to do that is the new String( ) constructor.

Quick Note:

If all you want to do is redirect the text from Request.Form back out to the user, then you don't need new String( ). But if you need to act upon the text with a JavaScript Function or Method, then you will need new String( ).

Without new String( ):

Take a look at the line I printed below.

var WebPageVariable = Request.Form("WebPageVaraible").toUpperCase();

ERROR! The Line Above Will Throw An Error because Request.Form("WebPageVaraible") is an ASP Object, and toUpperCase( ) is a JavaScript method.

Microsoft JScript runtime error '800a01b6'

Object doesn't support this property or method

/asp/Section01/script03b.asp, line 9

Moving Forward:

Now that we have Escape Characters and new String( ), everything else we want to do in ASP JavaScript becomes a lot easier.

You ain't seen nothing yet. We can mix and match JavaScript functions and methods with VBScript functions and methods. VBScript and JavaScript functions can pass arguments back and forth. They work wonderfully together. That will be the subject of lesson 04.

lesson04.asp Using VBScript with JavaScript

Get Started:

You can get JavaScript and VBScript to sing from the same sheet of music. Consider the script below.

<%@LANGUAGE="JavaScript"%>

<SCRIPT LANGUAGE="JavaScript" RUNAT="Server">

function JSGreeting()

{

return "Greetings from a JavaScript Function";

}

</SCRIPT>

<SCRIPT LANGUAGE="VBScript" RUNAT="Server">

Function VBGreeting()

VBGreeting="Greetings from a VBScript Function"

End Function

Function toDollars(x)

toDollars=FormatCurrency(x)

End Function

</SCRIPT>

<%

var a = 2;

var b = 2;

var c = add(a,b)

c += " (Two numbers are added by JavaScript, "

c += "and then formatted into currency by VBScript.)"

function add(x,y)

{

result = x + y;

result = toDollars(result);

return result;

}

Response.Write("<HTML>\r")

Response.Write(JSGreeting() + "<BR>\r")

Response.Write(VBGreeting() + "<BR>\r")

Response.Write(c + " <BR>\r")

Response.Write("</HTML>\r")

%>

Click Here to run the script in a new window.

RUNAT:

Let me pick this apart from top to bottom. Directly below is a simple stand-alone JavaScript.

<SCRIPT LANGUAGE="JavaScript" RUNAT="Server">

function JSGreeting()

{

return "Greetings from a JavaScript Function";

}

</SCRIPT>

This looks like any simple JavaScript you might find on the client side except for this little number: RUNAT="Server".

The RUNAT attribute tells the server to execute on the server, so the client never sees it. You can also set RUNAT="Client" in which case the Script would be passed along as-is to the web browser.

By the way, <SCRIPT LANGUAGE="JavaScript" RUNAT="Server"> should NOT be put inside ASP flags.

Take a look at the VBScript directly below.

<SCRIPT LANGUAGE="VBScript" RUNAT="Server">

Function VBGreeting()

VBGreeting="Greetings from a VBScript Function"

End Function

This VBScript does exactly the same thing as its JavaScript counterpart. There's nothing terribly special about it.

The Invocation:

There is, however, something special about the following VBScript.

Function toDollars(x)

toDollars=FormatCurrency(x)

End Function

The above function will take an argument from a JavaScript Function. Then it will return the appropriate value to the JavaScript function. Let me show how Function toDollars(x) is invoked.

function add(x,y)

{

result = x + y;

result = toDollars(result);

return result;

}

function add(x,y) is a JavaScript function. Halfway into the function, there is the following line:

result = toDollars(result);

The above line is in fact a call from a JavaScript function to invoke a VBScript function. How about that!

Warning:

Just one caveat. When you create scripts using the RUNAT attribute there is in fact an order of execution. I won't go into it now, because the order of execution is situational.

Here's what I will get into: Use scripts with the RUNAT attribute only for functions (and those global variables called inside functions). DON'T put top level code into it. You have no guarantee that top level code will execute in order using this technique.

lesson05.asp Bringing It Together:

Two Lines of Defense, One Function:

What if you could coordinate the client side and server side with the exact same functions? Form field validation comes to mind. It's not that hard for someone to copy your HTML into another script, and then alter the client side form field validation.

The obvious solution is to put form field validation on the server side. But that means a return trip to the server for every little error the user makes. So, how about getting the best of both worlds? Not only that, but how about using the exact same JavaScript function on both the client and the server, so as to ensure perfect consistency.

Take a look at the snippet below, and take particular notice of the function checkMyZip().

<%@LANGUAGE="JavaScript"%>

<%

//No ASP Here, just a regular HTML Page

%>

<HTML>

<SCRIPT LANGUAGE="JavaScript">

<!--Hide

function checkMyZip(zipCode)

{

var myRegularExpression=/(^\d{5}$)|(^\d{5}-\d{4}$)/

if (myRegularExpression.test(zipCode) == true)

{

return nothingIsWrong();

}

else

{

return somethingIsWrong();

}

}

function nothingIsWrong()

{

//Do nothing

return true

}

function somethingIsWrong()

{

alert("Something is wrong with the zip code you provided.")

document.zipCodeForm.zipCodeText.focus()

return false;

}

//Stop Hiding-->

</SCRIPT>

<STRONG>Type a valid U.S. Postal zip code into the box, and submit it.</STRONG>

<FORM NAME="zipCodeForm" ACTION="script05a.asp" METHOD="Post"

onSubmit="return checkMyZip(document.zipCodeForm.zipCodeText.value)">

<INPUT TYPE="Text" NAME="zipCodeText"<BR>

<BR>

<INPUT TYPE="Submit" VALUE="Submit">

</FORM>

</HTML>

Click Here to run the script in a new window.

One of the strongest arguments in favor of using JavaScript as your primary ASP scripting language is just exactly what we're seeing in this lesson. Take a look at the script below and once again take notice of the function checkMyZip().

<%@LANGUAGE="JavaScript"%>

<%

function checkMyZip(zipCode)

{

var myRegularExpression=/(^\d{5}$)|(^\d{5}-\d{4}$)/

if (myRegularExpression.test(zipCode) == true)

{

return nothingIsWrong();

}

else

{

return somethingIsWrong();

}

}

function nothingIsWrong()

{

//Do nothing

return true

}

function somethingIsWrong()

{

return false;

}

var zipCode=new String(Request.Form("zipCodeText"))

if (checkMyZip(zipCode)==true)

{

Response.Write("<HTML>\r")

Response.Write("The zip code you provided... ")

Response.Write("<FONT COLOR=\"RED\">")

Response.Write(zipCode + "</FONT> is good.\r")

Response.Write("</HTML>\r")

}

else

{

Response.Write("<HTML>\r")

Response.Write("The zip code you provided... ")

Response.Write("<FONT COLOR=\"RED\">")

Response.Write(zipCode + "</FONT> has a problem.\r")

Response.Write("</HTML>\r")

}

%>

It's not the most eloquent example, but it gets the point across. The primary function that validates data is exactly the same client side and server side. The supporting functions are not the same but the changes there are obvious.

Just for fun, look at then run the script below. There is no client side validation.

<%@LANGUAGE="JavaScript"%>

<%

//No ASP Here, just a regular HTML Page

%>

<HTML>

<STRONG>Type a zip code (with no client side validation)

into the box submit it.</STRONG>

<FORM NAME="zipCodeForm" ACTION="script05a.asp" METHOD="Post">

<INPUT TYPE="Text" NAME="zipCodeText"<BR>

<BR>

<INPUT TYPE="Submit" VALUE="Submit">

</FORM>

</HTML>

Click Here to run the script in a new window.

Concluding Section 01:

This concludes Section 01 of the lesson plan. Those who have experience writing ASP in VBScript don't need to go any further on this site. They can now use their client side JavaScript skills to convert any function (subroutine), any page, or any application to JavaScript.

The rest of us must continue the journey in Section 02.

lesson06.asp The Response Methods

The Response Object:

Response is one of six (6) ASP Objects. It represents the server's response to a web browser. Response has eight (8) methods, nine (9) properties, and one (1) collection. In this lesson we will focus on the methods.

Methods:

Response Methods
AddHeader( ) / Response.AddHeader("myHeader","My Value")
Add your own HTML Header(s)
AppendToLog( ) / Response.AppendToLog("My log message")
Send a message to the server log
BinaryWrite( ) / Response.BinaryWrite(binaryData)
Writes binary data such as pictures etc.
Clear( ) / Response.Clear()
Clears buffered response if Response.Buffer = true
End( ) / Response.End()
Ends the response
Flush( ) / Response.Flush()
Sends buffered response if Response.Buffer = true
Redirect( ) / Response.Redirect("
Redirects browser to different page
Write( ) / Response.Write(variables + " and text")
Outputs response to the browser

In JavaScript, the ASP Methods utilize parenthesis. Please notice that two of the methods depend upon Response.Buffer, which we will cover in the next lesson. Also, notice that if you use AddHeader() or Redirect(), then they must execute prior to Write().