Developer

Put these ASP sample scripts to use

Test sample scripts for writing information to the screen, processing forms, and more.

By Amy Cowen
(6/29/99)

Now that you're ready to dig in, here are some sample scripts you can put to use. You can even use includes to create a master file of these scripts and then add them to several pages.

Remember: When you embed HTML code inside an ASP script, you need to double your double quotes. So instead of

COLOR="#FF0000"

you use

COLOR=""#FF0000""

Make this a habit from your very first script!

Writing information to the screen
Whenever you want to write information to the screen, use Response.Write. It's best to keep chunks of script together whenever possible. To that end, you can put HTML tags directly into your scripts so you don't have to come out of the <% %> delimiters. Take a look at this snippet of code:

The code sample below for creating redirects and Go menus uses Response.Write to write both static HTML and ASP values to the screen. Your static content, including HTML tags, goes in quotation marks. The ASP variables remain outside of the quote marks. And, you concatenate the information with ampersands:

<% Response.Write "Today's date and time is: " & now & ". Where has the year gone?" %>.

<%
' other code removed ...
dim strCompany
strCompany = objRec("Company")
strLogo = objRec("Logo")
Response.Write "<TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0 WIDTH=400><TR><TD>"
Response.Write "<FONT COLOR=""green"" SIZE=""+1""><B>" & strCompany & "</B></FONT></TD>" Response.Write "<TD><IMG SRC=""/logos/" & strLogo & ".gif"" ALT=""Logo"">"
Response.Write "</TD></TR></TABLE>"
' more code follows...
%>

As you can see, standard text is combined with the now variable and strung together using ampersands. Common mistakes include omitting the quotes surrounding HTML tags and static text and forgetting about the ampersand—so be careful!

Although it is recommended that you keep as much code together as you can, there will be times when you intermix your HTML and ASP code like this:

<%= strCompany %>.

This code chunk produces the same line of text as the previous sample, but this time, instead of Response.Write, we've put the ASP directly into the HTML code and used a shortcut for Response.Write:

<%=.
Cache no more

If you've got corporate clients, you may be familiar with caching problems related to proxies. Each browser caches information differently, and users can set their own caching criteria in their user preferences.

Whether it's user choice or a proxy problem, the end result is that your visitors and/or your clients may be seeing stale content. As you begin to add more dynamic content, caching begins to play an even more problematic role. With ASP, you can simply turn caching off by setting the expiration date for your pages to zero.

Adding

<% Response.Expires = 0 %>

to the top of your pages sets the page to expire immediately, so it will be reloaded each time it is hit by a user.

Creating redirects and Go menus
Using client-side redirects like META HTTP-EQUIV="REFRESH" works, but the ASP solution is both easier and faster.

When your company attaches an URL to a promotional campaign, the page shown by that URL is often a replica of another core page—for example, index.asp or products.asp. Using ASP, you can set up simple redirects for campaign URLs. This lets you use a catchy URL for the campaign without keeping multiple copies of the content in synch. Instead, when users hit the catchy URL, they are immediately redirected to the appropriate page:

<%
Response.Redirect "/index.asp"
%>
You don't need anything else on the page, and you can use relative or absolute URLs.

Go menus
Drop-down menus can be excellent alternative forms of navigation. Part of their beauty is that they can house ancillary links you want to be accessible—just in case someone is looking for them—but for which you don't want to create a text link or a visual button in your main navigation.

You may have had trouble with JavaScript drop-downs in the past, but using Response.Redirect to process a drop-down menu short-circuits problems associated with browser support of client-side scripting. There are a number of ways you can handle the menu, but here's a plug-and-play way to get started.

<FORM METHOD="post" ACTION="drop.asp">
<TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0>
<TR><TD><FONT SIZE="-1">
<SELECT NAME="dropbox" SIZE="1">
<OPTION VALUE="http://www.builder.com">Explore Builder.com
<OPTION VALUE="http://www.cnet.com">Explore CNET.com
<OPTION VALUE="http://www.builder.com/Authoring/HomeSite/">HomeSite Tips and Tricks
<OPTION VALUE="http://www.builder.com/Authoring/Dreamweaver/">Dreamweaver 2.0 Tips
<OPTION VALUE="http://www.builder.com/Authoring/XmlSpot/">Spotlight on XML
<OPTION VALUE="http://www.builder.com/Business/Freelancing/">Be a Freelance Web Builder
<OPTION VALUE="http://www.builder.com/Programming/VBScript/">VBScript Tips and Tricks
<OPTION VALUE="http://www.builder.com/Authoring/Dreamweaver/">Dreamweaver 2.0 Tips
</SELECT>
<INPUT TYPE=SUBMIT VALUE="Go!">
</FONT></TD></TR>
</TABLE>
</FORM>
The corresponding drop.asp file would process the selection and instantly send the browser to the selected site or page:

Processing forms
Dealing with forms is often a stumbling block for an HTML coder. The front end is a breeze, but processing the form often can be unpredictable. Mailto forms are unreliable, and even canned CGI/Perl solutions can be tricky. ASP makes dealing with form data easy.

When you use the GET method to process a form, all of the user-entered data is strung together in the URL. You can tap into this data using Request.QueryString.

This sample shows both the front end of a form and the page that processes the form: form.asp and post.asp.

Form.asp

<FORM ACTION="post.asp" METHOD="GET">
<B>First Name:</B> <INPUT TYPE="Text" NAME="fname">
<P>
<B>Last Name:</B> <INPUT TYPE="Text" NAME="lname">
<P>
<B>Birth Month:</B>
<SELECT NAME="month" SIZE="1">
    <OPTION VALUE="January">January</OPTION>
    <OPTION VALUE="February">February</OPTION>
    <OPTION VALUE="March">March</OPTION>
    <OPTION VALUE="April">April</OPTION>
    <OPTION VALUE="May">May</OPTION>
    <OPTION VALUE="June">June</OPTION>
    <OPTION VALUE="July">July</OPTION>
    <OPTION VALUE="August">August</OPTION>
    <OPTION VALUE="September">September</OPTION>
    <OPTION VALUE="October">October</OPTION>
    <OPTION VALUE="November">November</OPTION>
    <OPTION VALUE="December">December</OPTION>
</SELECT>
<P>
<INPUT TYPE="Submit" NAME="submit" VALUE="Submit">
</FORM>
Post.asp
<%
  strFirstName = Request.QueryString("fname")
  strLastName = Request.QueryString("lname")
  strBirthMonth = Request.QueryString("month")
%>
<HTML>
<HEAD>
  <TITLE>Success!</TITLE>
</HEAD>
<BODY>
Thank you! The information shown below has been received:
<BR>
  <UL>
  First Name: <%= strFirstName %>
  <BR>
  Last Name: <%= strLastName %>
  <BR>
  Birth Month: <%= strBirthMonth %>
  </UL>
</BODY>
</HTML>
If you look closely at the ASP code on post.asp, you'll see how Request.QueryString works. After filling in the information on form.asp, the user clicks Submit. That information is passed in the URL. So, you might see:
http://yourserver/post.asp?fname=Peter&lname=Pan&month=June&submit=Submit.
You can see the data encoded here, but rather than deciphering it yourself, let the browser parse the data and spit it back out. Using Request.QueryString, you can pick any of the fields that follow the question mark and write the value. How do you know what fields are available? You defined them using the NAME attribute for each form INPUT TYPE. So, because form.asp uses <INPUT TYPE="Text" NAME="lname">, I know there will be a lname= value. I can request that and assign the value to a variable using this line:
strLastName = Request.QueryString("lname").
Using the URL shown above, the value of strLastName will be Pan. So, when, for whatever reason, I am ready to write that value to the page, I can just write the value of strLastName:
<%= strLastName %>.
Processing forms: POST
If you use POST to process a form, you can still access the data, but this time you use Request.Form rather than Request.QueryString. The only change you would make to form.asp is to set METHOD=POST. Here's how you would read the form values in post.asp:
<%
strFirstName = Request.Form("fname")
strLastName = Request.Form("lname")
strBirthMonth = Request.Form("month")
%>
The syntax above is almost identical to that used in the Request.QueryString example. Using the Request object makes it easy for you to access important form data and doesn't require a lot of legwork!

Using case to determine outcome
Using SELECT CASE is one way to test for the value of a field or variable and direct the server to do something based on that value.

You set up a case for each value you want to check. For example, if you wanted to deliver a specific line based on which day of the week it is, you could use the following SELECT case script:

<% currentdate = vbShortDate
  ' use the built-in VBScript constant vbShortDate
' to see what day of the week it is.
  ' define what variable is being tested
select case currentdate
case vbSunday
response.write "Today is Sunday. We're not working!"
case vbMonday
response.write "It's Monday. Back to work..."
case vbTuesday
response.write "T-t-t-tuesday..."
case vbWednesday
response.write "It's Hump-Day!"
case vbThursday
response.write "Today is Thursday. One more to go."
Case vbFriday
Response.write "TGIF!"
Case vbSaturday
Response.write "Sorry, I don't register scripts on Saturday."
end select %>
You could also set this up using if...then tests. In many cases, however, the SELECT CASE test can simplify your code, especially when you've got a finite set of possible answers to check.

We can turn the previous example into something more functional by using SELECT CASE to highlight a specific product on a given day with this slight variation of the file. (See Request.QueryString.)

<% currentdate = vbShortDate
select case currentdate
%>
<% case vbSunday %>
<!— #INCLUDE FILE="sunday.inc" —>
<% case vbMonday %>
<!— #INCLUDE FILE="monday.inc" —>
<% case vbTuesday %>
<!— #INCLUDE FILE="tuesday.inc" —>
<% case vbWednesday %>
<!— #INCLUDE FILE="wednesday.inc" —>
<% case vbThursday %>
<!— #INCLUDE FILE="thursday.inc" —>
<% case vbFriday %>
<!— #INCLUDE FILE="friday.inc" —>
<% case vbSaturday %>
<!— #INCLUDE FILE="saturday.inc" —>
<% end select %>
Here, we've used the same premise for using SELECT CASE to determine what day of the week it is, but instead of writing something trivial, we've created a low-tech but highly functional set of dynamic content. Each day of the week has its own include file. The include file used depends upon the results of the SELECT CASE test. (To test this script, just make sure you have a dummy copy for all include files mentioned.)

Rotating content and ads
Using the content rotator, you can quickly implement a random content feature on your site. All you have to do is create a Content Schedule File.

The Content Schedule File is a text file that holds the chunks of content that will be rotated in and out. Each chunk can contain HTML code (tables, images, links, and so on), so don't feel limited to simple lines of text. You can also weight the content so the frequency that an item appears depends upon its value. Here's a sample content schedule file for a Cool Site of the Day feature:

Contents of sites.txt

%% // "Comment" the text after the hash marks on the first line
<FONT FACE="Arial,Helvetica" COLOR="green">When you've got an ASP question, head to <A HREF="http://www.activeserverpages.com">ActiveServerPages.com</A>.
</FONT>
%%
<FONT FACE="Arial,Helvetica" COLOR="blue"><
A HREF="http://www.4guysfromrolla.com/">4GuysFromRolla</A> is packed with great ASP samples.
%%
<FONT FACE="Arial,Helvetica" COLOR="red">Rummage through <
A HREF="http://www.tcp-ip.com/ASPIndex/WebLinks.asp?cat=ASP">The ASP Toolbox7lt;/A> for good ASP tips and tricks.
%% #2
<FONT FACE="Arial,Helvetica" COLOR="green">Microsoft's online documentation for Active Server Pages, in the <A HREF="http://msdn.microsoft.com/library/default.htm">MSDN Online Library</A>, is definitely worth a bookmark!

Of the four snippets above, only the last one has a value: #2. The others all default to a value of 1. The higher the number, the more important it is in the rotation, and the more frequently it will appear.

Now that our content file is ready, we can call it from our .asp page by adding the following ASP information:

<%
Set CoolSite = Server.CreateObject("IISSample.ContentRotator")
CoolSite = ContRot.ChooseContent("sites.txt")
Response.Write CoolSite
%>
Load up your page to see the rotation in action. Ctrl-R will refresh the page, so you can repeatedly reload the page to see the content change.

Rather than using Server.CreateObject to instantiate the Content Rotator component, you can add the following snippet to your global.asa file:

<OBJECT RUNAT=Server SCOPE=Application ID=ContRot
ProgID="IISSample.ContentRotator">
</OBJECT>
If you don't already have a global.asa file, create one. Just paste the above lines into a blank text file and save it as global.asa in the same virtual directory as the pages with which you're working. To see another example of the Content Rotator, run the Fortunes.asp sample included with the Microsoft NT Option Pack 4 Product Documentation.

Rotating ads
The ad rotator works similarly to the Content Rotator, but it has been designed specifically to hold ads, so it has built-in ad-specific features.

Like the Content Rotator, the Ad Rotator uses a text file to hold the banners and associated information, such as size, URL, and ALT-text. There are two parts to the schedule file, separated by a blank line with an asterisk (*) on it. The first part allows you to set variables that will apply to all the ads in the rotation: [REDIRECT URL], [WIDTH numWidth], [HEIGHT numHeight], [BORDER numBorder]. All four of these variables are optional. (If you leave them out, just make sure to use an asterisk (*) before beginning the second section, which holds the individual banners.)

In the second half you can set the following variables:

  • AdURL—the path for the banner image file
  • AdHomePageURL—the URL used when the user clicks the banner
  • Text—the ALT-text
  • Impressions—the weight of the ad. According to Microsoft, "if a Rotator Schedule file contains three ads with impressions set to 2, 3, and 5, the first advertisement is displayed 20 percent of the time, the second 30 percent of the time, and the third 50 percent of the time."

Here's a sample file that holds information for three banners and uses the variables described above:

WIDTH 400
HEIGHT 60
BORDER 0
*
http://www.myserver.com/ads/companya.gif
http://www.companya.com/
Visit Company A!
20
http://www.myserver.com/ads/companyb.gif
http://www.companyb.com/
Visit Company B!
20
http://www.myserver.com/ads/companyc.gif
http://www.companyc.com/
Visit Company C!
60
To instantiate the ad rotator on your page, add this snippet of ASP code:
<%
Set Ads = Server.CreateObject("MSWC.AdRotator")
Response.Write Ads.GetAdvertisement("ads.txt")
%>
Notice that ads.txt is the name of the text file. You can give the file any name you like—just make sure you use the proper path to the file.

Sending e-mail with ASP
There are a number of components you can use to handle email functions with ASP, but Collaboration Data Objects (CDO) is installed on many NT Servers running IIS (NT Option Pack 4), so it's a canned option for mail processing.

Here are the basic elements for using CDO:

<%
Set objCDOMessage = Server.CreateObject("CDONTS.NewMail")
' creates the object
  objCDOMessage.From = "webmaster@theflap.com" ' the address listed as "From"
objCDOMessage.To = "cybercow@wco.com" ' the address listed as "To"
' you could include bcc and cc recipients as well
objCDOMessage.Subject = "Thank You for Adding a Title!" ' specify the subject header
objCDOMessage.Body = "Thanks for taking the time to add a book to our list." & vbcrlf &_
"Here is the information you entered: " & strBookTitle & strBookAuthor
  'now send the message
objCDOMessage.Send
'wrap things up
Set objCDOMessage = Nothing
%>

Editor's Picks

Free Newsletters, In your Inbox