Article

Handling Submitted Data with ASP

Page: 1 2 3 4 Next

The Request Object

When a Web browser requests a Web page from a Web server, it can send a lot more information than just a simple URL. For instance, if the user submits a form to make the request, then everything the user typed into that form is sent along with the page request. If the user has been assigned a unique session ID that maintains, for example, a shopping basket of catalogue items they’ve chosen to buy, then that session ID will usually be sent, along with every page request to that site, as a cookie.

If you're comfortable with the concept of a Response object that handles the process of sending a Web page to the requesting browser, then it should also make sense to you that there is a Request object that takes care of all the details of the request as well.

The most common use for the Request object is to retrieve information that was sent by the browser along with the request. These values can come in several forms:

  • defined in the query string
  • submitted as part of a form
  • stored in cookies

For each of these, the Request object has a special property type called a collection, which contains all the values submitted via each of these methods as part of the request. To demonstrate, let's start with the simplest method for passing information along with a page request – the query string.

Query Strings

In case you're not familiar with query strings, the basic idea is to tack on a set of variables to the end of the URL that appears in the browser's Address field. For example, if there were a page on your site with URL http://www.yoursite.com/welcome.asp, then you could send that page my first and last name by adding a query string to the address as follows:

http://www.yoursite.com/welcome.asp?firstname=Kevin&lastname=Yank

The portion of the URL that’s in bold is the query string. A query string always begins with a question mark (?), which marks the end of the standard URL. The query string, which follows the question mark, is a series of one or more name/value pairs separated by ampersands (&). In this case, we have two such pairs. The variable name firstname is given a value of Kevin, and the variable name lastname is given a value of Yank.

When a URL like this is used to load an ASP page, the name/value pairs become accessible through the QueryString collection in the Request object. For example, you can print out the query string that was sent with a request as follows:

Response.Write "Query string: " & Request.QueryString

For the above example, the output would look like this:

Query string: firstname=Kevin&lastname=Yank

When passing more than one value like this, however, you'll usually want to be able to retrieve these values separately, and that’s where the fact that the QueryString property is a collection, comes in handy. For instance, to retrieve and print out the value of the firstname variable defined in the query string above, you would use this code:

Response.Write "First name: " & Request.QueryString("firstname")

The above line specifies that we’re only interested in the value of the firstname variable defined in the query string. The line output by this code will look like this:

First name: Kevin

Variables in a query string can have multiple values. Consider the following address, which might be seen on a Web site that provided a currency converter:

convert.asp?currency=CAD&currency=USD&currency=AUD

As you can see, this query string contains three name/value pairs, all three of which assign a different value to the currency variable. On our hypothetical currency converter site, such a request might be used to ask for the current exchange rates for Canadian dollars, US dollars and Australian dollars. Upon receiving this request, if convert.asp were to print out the value of the currency variable (Request.QueryString("currency")) as we demonstrated above, it would produce the following output:

CAD,USD,AUD

A more useful way to process this value would be to consider each of the three values one at a time. This can be done using the Count property of the QueryString("currency") value, which contains a count of the number of values submitted (in this case, 3). Here's roughly what the code would look like:

For i = 1 To Request.QueryString("currency").Count  
 currency = Request.QueryString("currency")(i)  
 ' Process currency...  
Next

In the above code, Request.QueryString("currency").Count will have a value of 3, so the loop body will be processed three times. The first time through the loop, the loop variable i will have a value of 1, and so currency will be assigned the value Request.QueryString("currency")(1). This refers to the first of the three values assigned to the currency variable in the query string, and will yield "CAD". Similarly, the two subsequent iterations of the loop will yield "USD" and "AUD" respectively.

As another example, let's say you wanted to add a personal touch to your Web site by greeting your visitors by name on every page. Here's the code for a basic page on such a site:

1  <% Option Explicit %>  
2  <%  
3    
4  If Request.QueryString("username").Count < 1 Then  
5    ' User has not given his/her name  
6    %>  
7    <html>  
8      <head>  
9        <title> Welcome! </title>  
10     </head>  
11     <body>  
12       <form action="<%=Request.ServerVariables("SCRIPT_NAME")%>"  
              method="GET">  
13         <p>Please enter your name:  
14           <input type="text" name="username">  
15           <input type="submit" value="OK"></p>  
16       </form>  
17     </body>  
18   </html>  
19   <%  
20   Response.End  
21 End If  
22    
23 Dim name  
24 name = Request.QueryString("username")  
25    
26 %>  
27    
28 <html>  
29   <head>  
30     <title> Typical Page </title>  
31   </head>  
32   <body>  
33     <p>Hi, <%=name%>!</p>  
34     <p>Click <a href="page2.asp?username=<%=Server.URLEncode(name)%>">  
         here</a> for more.</p>  
35   </body>  
36 </html>

Since this is the most complex ASP script we have seen so far, and because there are a couple of new tricks in there, I'll explain the important lines one at a time:

4  If Request.QueryString("username").Count < 1 Then

The condition of this If-statement checks whether the Count property of the username variable in the query string is less than one. This will only occur when no value has been submitted for that variable as part of the query string, in which case the Count will be 0. When this condition occurs, instead of displaying the normal content of the page, the script will display a simple form prompting the user for his or her name.

6    %>

While we could have used Response.Write commands to output the HTML for the form to be displayed, a simpler option is to switch out of ASP mode inside the If-statement. Just like statements appearing in this spot, the HTML code on lines 7 through 18 will only be displayed if the condition in the If-statement is true.

12       <form action="<%=Request.ServerVariables("SCRIPT_NAME")%>"  
              method="GET">

As complicated as this line may look, it’s actually just a standard HTML <form> tag. For those of you who are unfamiliar with forms, I'll explain what the two attributes, action and method, do.

The action attribute specifies the URL of the script to which the browser should submit its request (along with the information entered in the form). In this case, once the user has entered his or her name, we want to submit the form to the very same script that generated it, so that the user is then presented with the page he or she originally requested. If you simply typed in the filename of this script, it would work fine, except that if you ever renamed the file, you'd have to remember to come back and change the value of this attribute as well. Also, it makes the code harder to reuse on every page of your site if you have to remember to type in the filename of the page each time you use it. The alternative is to use ASP to print out the name of the file, which is exactly what the code above does. You should recognize <%=...%> as the shortcut for printing out an ASP value in the middle of a piece of HTML. The value being printed out in this instance is a member of the Request.ServerVariables collection, which contains all sorts of useful values. We won't be looking at this collection in detail at this time; however, I'll explain any values we use from it as they come up. The "SCRIPT_NAME" value that we use here always contains the path and filename of the ASP script that was requested, as it appears in the URL. Thus, we can print it out as the value of the form's action attribute, to make the browser submit the request back to the very same page.

The method attribute allows you to specify one of two ways for the form to submit its values. When set to "GET", as it is here, the values entered into the form field are converted into name/value pairs and tacked onto the end of the URL specified by the form's action attribute. In short, "GET" tells the browser to submit the form as a query string. The alternative, "POST", tells the browser to submit the values in the body of the HTTP request. Basically what this means is that the values do not appear as part of the URL (good for submitting sensitive information like credit card numbers or passwords), but instead, they’re hidden inside the request. We'll see how to retrieve values submitted this way momentarily.

14           <input type="text" name="username">

This tag creates a text input field that, when it’s completed by the user and submitted as part of the form, creates a variable called username in the query string.

20   Response.End

As we’ve seen before, this line causes the script to stop processing, and send all the output generated so far to the browser. This prevents the user from seeing the actual content of the page until he or she has filled out the form with his or her name.

23 Dim name  
24 name = Request.QueryString("username")

Once we’ve determined that a name has been provided in the query string, we declare a variable, and store the name from the query string in it. We could have just continued to refer to the value as Request.QueryString("username") for the rest of the script, but name is a more convenient way to refer to it, and saves typing.

33     <p>Hi, <%=name%>!</p>

We can then use the variable to display the person's name as part of a personalized greeting at the top of the page! All that's left is to ensure that the value is passed on to other pages on the site, which presumably have the same block of code at the top to prompt the user for a name if one is not provided in the query string. To ensure that the user isn't prompted on every single page he or she views, you must code your HTML links so that they contain a query string with the user's name in it. The following line contains such a link:

34     <p>Click <a href="page2.asp?username=<%=Server.URLEncode(name)%>">  
         here</a> for more.</p>

You might have expected the link to be "page2.asp?username=<%=name%>"; however, because of the rules that apply to URL's, you can't put just any value into a query string. Spaces, for example, are not allowed; nor are most non-alphanumeric characters. To include such characters in the value of a query string variable, they must be encoded. Spaces, for example, are inserted as plusses (+). Other characters are inserted as a percent sign followed by their ASCII character codes.

ASP provides another built-in object (like Request and Response) called Server that contains a number of useful methods for performing miscellaneous tasks. The URLEncode method, used in the line above, takes a text string and converts it into the encoded for required for use in a query string. Thus, to place the name variable in the query string for our link, we must pass it through the URLEncode method as shown above.

That's all there is to it! Save the file as an ASP script and try it out on your own server. When you first load the page, you'll be presented with a form that prompts you for your name.

A form prompts the user to enter a name.

Once you've entered your name, as I have above, and clicked 'OK', the page will reload and display the welcome message and a simple link.

The resulting page is personalized with the name entered.

Notice that the URL has changed to include a query string with the value you entered into the form field. Notice also that the space in the value I entered was automatically encoded as a plus (+) by the browser. Finally, move your mouse over the link to check that the URL was correctly generated with the appropriate query string to carry the value forward to the next page in the site.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links