In VBScript, you don't have to declare variables or explicitly define their type the way you do in other scripting languages. A variable exists the first time you use it. This feature leaves your code wide-open to typos, however. If you mistype a variable name somewhere in the code, a new variable is created. Your script may not work properly, and you may not even realize it.
Get in the habit of declaring your variables before you use them. All you have to do is type Dim variableName:
%<%Dim IntUserID%>%IntUserID is now ready for use. For another safety net, use Option Explicit. If you turn on Option Explicit, you'll get an error any time you use a variable that has not been defined. This may sound tedious, but it will clue you in to bugs that might otherwise be hard to track down.
To use Option Explicit, just put the following as the first line in your script:
<% Option Explicit %>If you want to see what happens when you forget to declare a variable, run this bit of code:
<% Option Explicit %>Because the strName variable (Dim strName) isn't defined, you'll see an error something like this:
<:% strName = Request.Form("Name") %>
Microsoft VBScript runtime error '800a01f4'Using Len
Variable is undefined: 'strName'
/e/oe-test.asp, line 10
You can determine the length of a string of text by using the Len(string) function.
<%If you're wondering how Len might come in handy, think about a common form in which you ask users to enter their five-digit zip code or select a three-digit PIN. Using Len, you could verify that enough numbers were entered.
IntString = "This is a Simple Sentence."
IntStringLength = Len(IntString)
Response.Write "There are " & IntStringLength & " characters (including spaces) in the sentence shown below:"
Response.Write "" & IntString & ""
Trimming strings is something you'll want to get in the habit of doing early on. Many times, a string will have an extra space at its beginning or end, and if you haven't trimmed it, you may waste time worrying over variables that should—but don't—match:
<% strName = Request.Form("Name")If the value of strName is " Amy Cowen" because that's how I typed it in the form box, then the test will fail even though both variables appear to be holding the same information. "Amy Cowen" doesn't equal " Amy Cowen."
strCheckName = "Amy Cowen"
If strName = strCheckName THEN
Response.Write "Success! The names matched."
Response.Write "Sorry. The names do not match."
Similarly, if you were pulling the Name field into a URL:
<% Response.Write " & objRec("Name") & "">Your Site" %>You would quickly run into problems if any of the records in the Name field had extra spaces.
You can trim an entire string or you can just run the process on the left or the right:
<% strComments = Request.Form("Comments")Assume the user had entered:
strComments = Trim(strComments)
" I am having problems installing the software I downloaded. "(Quotation marks are shown here just so you can see the blank spaces.)
The trim statement shown above would chop off the extra spaces, leaving:
"I am having problems installing the software I downloaded."Or, returning to our " Amy Cowen" example, I'll come up with a successful match if I add this to the script:
strName = Trim(strName)To trim the right side, use Rtrim(string). To trim the left side, use Ltrim(string).
An easy mistake to make when you're starting to use a language like VBScript is to try and compare an integer (512) to a string (512). If you don't realize that 512 isn't necessarily the same as 512, you can spin your wheels for a while trying to figure out why a given script won't work.
Take this scenario: You're passing the ID (intUserID) of a file to the ASP script. Using Request.QueryString (below), you'll determine the ID of the file the user wants to edit. You need to pull the information for that record from your database and write it to the screen. The ID in your database is likely to be an integer—especially if you've used the AutoNumber feature for that field. The ID you passed, however, may, in fact, be a string, depending on how you set up the variable. So, the two will never match unless you convert them to be the same type.
Using the FileSystemObject, you can test to see if a file—for example, *.html, *.asp, *.inc., *.gif—or directory exists. If the specified file does exist, of course, you would want one chain of events to occur. If the file doesn't exist, then you would want another chain of events to be put into motion. Use this code:
<%To test this file easily on your own system, add this to the top of the script:
sPath="/profiles/" & strFileName & ".asp"
if fe.FileExists(sFile) THEN
Response.Write "Yeah! I found it!."
Response.Write "You can access that file by "
Response.Write "<A HREF=""" & sPath & """>Clicking Here</A>."
Response.Write "Sorry. The requested file does not exist."
strFileName = "name"
' First assign the name of a file you have to this variable.
' strFileName holds just the name, not the extension or the path.
' Make sure you change the path for sPath to the virtual directory your file is in
' Run the script.
' Then come back and change the strFileName variable to the name of a file
' you do NOT have.
' Run the script.
Converting the passed variable to an integer is easy to do and can save you headaches later. The format is simple:
<%You can also comment your ASP code and use includes.
dim intUserID intUserID = Request.QueryString("userID")
intUserID = CInt(intUserID)
' intUserID is now an integer.
Commenting the Code
In ASP, a script is processed before it is sent to the browser. So, you don't need to use regular HTML comment tags to hide your scripts from older browsers. In fact, your scripts won't show up at all in the HTML source that is rendered by the browser, so older browsers aren't going to accidentally spit any code to the screen.
You may, however, want to use comments to annotate your ASP scripts for easy reference. In VBScript, you use the apostrophe to mark a comment:
currentdate = now
' make sure you use quotation marks around the HTML code
' the & serves to concatenate the string
Response.Write "Today is: " & currentdate & "<BR>"
In Jscript use // to designate comments.
If you've worked with .shtml files before, you already may be familiar with the power of includes. If not, then step up to the plate to meet one of the HTML coder's best friends.
An include is content that you store in a separate file. In standard HTML, includes often use the .inc extension. In ASP, you can use .asp, .txt, or .inc extensions. You then call that file into the HTML code. When the HTML file is delivered, the include information is pulled from the specified file and written directly to the screen as part of the HTML contents. So, if you do a View Source, the page you'll see will appear the same as if the entire page had been coded in a single static HTML file.
For regular HTML, includes can be enormous time-savers when it comes to creating a template for a site. Headers, footers, and navigation elements are just a few sections that may appear on numerous pages. When you use an include, you just type the file once and then call it when you need it. This has several advantages:
- To update the content, you change only one file.
- The include meat is separate from the HTML page/code, so anyone can make content changes to the page without accidentally messing up critical page elements or scripts.
- Your core HTML file is smaller and less unwieldy.
In ASP, includes are also invaluable. Scripts you'll be using over and over again—even something as simple as a connection string for your database—can be stored in an include and then dropped into place on individual pages as needed.
To include a file, you use either of these formats:
<!— #INCLUDE FILE="filename.inc" —>
<!— #INCLUDE VIRTUAL="/filename.inc" —>.
FILE references an include using a relative path. VIRTUAL references an absolute path in relation to the server. If you tend to move directories and files around, it's often easiest to use VIRTUAL as a default so you don't run into unexpected bugs later. On the other hand, when you're testing files locally, you may need to use FILE, depending on how you have your personal server configured.
In standard HTML, you generally use the .inc extension for your include files. In ASP, you can use .asp. This will prevent your files from being easily opened and read by others.