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

Basics: Request Yields Input From The Browser GET or POST

- Microsoft ASP technology is a server-side scripting technology used to generate HTML and access databases from server scripts. Programs consist of scripts executed by an interpreter within the server. - ASP.Net separates implementation logic from the user interface, but is more tightly integrated with Microsoft software and offers fewer language choices. - The document discusses ASP and ASP.Net basics, request and response objects, user interaction through forms, and server variables.

Uploaded by

jasbamra
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)
207 views

Basics: Request Yields Input From The Browser GET or POST

- Microsoft ASP technology is a server-side scripting technology used to generate HTML and access databases from server scripts. Programs consist of scripts executed by an interpreter within the server. - ASP.Net separates implementation logic from the user interface, but is more tightly integrated with Microsoft software and offers fewer language choices. - The document discusses ASP and ASP.Net basics, request and response objects, user interaction through forms, and server variables.

Uploaded by

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

Basics

Microsoft ASP technology is a server-side programming


technology primarily used to generate HTML and access
databases, files and any other server resource. Programs
consist of scripts executed by an interpreter (JavaScript,
VBScript, PerlScript, etc.) within the server space. One
advantage of ASP scripts is they are generally light-weight
to execute assuming the script interpreter is re-entrant
and can be managed by the server to limit resources
allocated to the script. The scripting languages are simple
to program but limited but can be extended via ActiveX
objects. A key disadvantage is ASP is not a cross-platform
standard across servers so moving applications from a
Microsoft Web server may be painful.

ASP.Net attempts to separate implementation logic (i.e.


programming) from the user interface; but it is more
tightly integrated into Microsoft software and offers fewer
industry standard choices of languages.

We will use ASP and JavaScript as these are most


commonly available in some version or flavor on other
servers.

Request and Response Objects


Request yields input from the browser GET or POST
methods. The value of the form input variable named
"BuyHigh" is given by:

• Request("BuyHigh")

Response outputs to the browser among other uses. To


output the string <h1>Hello</h1> from JavaScript:

• Response.Write("<h1>Hello</1>");

User Interaction
The main motivation for server-side programming is to
interact with the Web client by getting input from the client
and sending back HTML. There are three main HTML
methods for the client to send data back to the server from
HTML forms:

1. GET
2. POST
3. Send data as part of the URL, a ? is appended
to the URL followed by data. This will be examined
later in the course.

HTML <FORM>

Sending parameters to a server program from a HTML


input form uses the GET or POST method. The main
difference is that the GET passes parameters in the URL or
address so is limited to how much data can be passed. The
POST method passes parameters back to the server
through standard input so is effectively unlimited in the
amount of data that can be returned.

The following uses named parameters in HTML form as


program arguments. The <Input Type='Text'
name="myname"> defines a text box for input and the
parameter of myname.

Form GET Method

The GET method passes user data from the browser


to the server as part of the URL. The Get method
and form to input from a Text box is:
GetName.htm
<FORM Method='GET'
Action='http://localhost/A348/GetName.asp'>
Enter your name: <Input Type='Text'
name="myname"><br>
</FORM>
• GET - Form data is passed to server appended to the
URL.
• Action - The URL when user presses the Enter key.
• Text - The browser renders a text box for user input.

• myname - The name of the text box. Suppose that


ABC is entered into the text box. Browser will send
myname=ABC for the myname text box value.
The browser passes the parameters to the server
appended to the URL, the server passes the

parameters to the ASP program in a Request


variable. The GetName.asp program reads the
variable and parses out the "myname=" string and
assigns whatever string follows to the character
array myname. The steps followed are roughly:

1. Load the GetName.htm file into the


browser, enter Ray, and press Enter.
2. The form instructs the browser to send
request http://localhost/A348/GetName.asp?
myname=Ray which executes the
GetName.asp program with parameter data
myname=Ray.
3. The GetName.asp program requests the
value of myname giving the response output
of:
<H1>Hello Ray</H1>
4. The output of <H1>Hello Ray</H1> is
passed back from the server to the browser
which renders the HTML.

Points of note:

o Request("myname") - Returns the string


"Ray".
Form POST Method

The POST method differs from the GET by sending


user data to the server, not appended to the URL,
but as an input stream. The server passes the data
stream to the ASP program on standard input so
essentially the amount of data sent from the browser
client is unlimited.
In ASP, the Request object handles GET and POST
identically.

Server variables
The operating system maintains state in part through the
use of global variables. At the Command prompt these
variable can be displayed by the SET command.

SET

COMPUTERNAME=RAY
ComSpec=C:\WINDOWS\system32\cmd.exe
HOMEDRIVE=C:
NUMBER_OF_PROCESSORS=2
OS=Windows_NT
Path=c:\apps\imagemagick-6.2.1-q16;C:\apps\
PROCESSOR_ARCHITECTURE=x86
PROCESSOR_IDENTIFIER=x86 Family 15 Model
2
PROMPT=$P$G
SystemRoot=C:\WINDOWS
USERNAME=ray
The server and operating system maintain a large number
of server variables that can be examined by an ASP
program. The following prints all server variables back to
the browser. Note that the browser output has been edited
to reduce size.
The ServerVariables collection has the following properties:
• Item - The value of a specific item by name.
For example, the following are equivalent, returning
the value of SERVER_PORT, normally 80:
o Request.ServerVariables.Item("SERVER_
PORT")
o Request("SERVER_PORT")
• Key - Returns the name of a specific in the
collection. The following returns the string
"SERVER_PORT":
o Request.ServerVariables.Key(38)
• Count - The number of ServerVariables in the
collection. Example:
o Request.ServerVariables.Count()

The server variable QUERY_STRING contains any form


variables returned by the GET method.

ASP Object

Objects are a way of encapsulating multiple methods


(they're like functions) and variables in one easy to
manage Uber-Variable (an Object). Objects in ASP
resemble other Object Oriented Programming
languages. In this lesson we will be using the ASP
CDO.Message object as our example object to be
dissected.
ASP Object Overview

Objects were created to combat the increasing complexity of programming. The rationale for
understanding and using Objects in your programming is to make programming easier and your code
more human readable.

ASP Create an Object - Server.CreateObject

An object in ASP is created by passing a name string to the Server.CreateObject function(actually


referred to as a method). The string to create a Message object is "CDO.Message". We will be
creating a CDO.Message object in this example.
Note: Because objects are special there is a special way that you create and destroy them using the
Set keyword. These areas are marked in red in the example below.
ASP Code:
<%
Dim myObject
Set myObject = Server.CreateObject("CDO.Message")

'You must Set your objects to "nothing" to free up the


'the computer memory that was allocated to it
Set myObject = nothing
%>

That wasn't too painful, was it? Let's cover some more bases on the object model.
Objects are a collection of related things that are combined into this blob of programming goo that can
be created and destroyed whenever we may need it. For example say that you wanted to make an
object that allowed you to send an email...
Well there are certain things all emails have: To, From, CC, Subject, etc. This list of variables that are
common to every email would be quite tiresome to have to create for every email we sent. Wouldn't it
be nice if we could create some sort of Uber-Variable(Object) that would group all these smaller
variables into one thing?

ASP Object Properties

These smaller variables are commonly referred to as an object's properties and the format for setting
these properties is nearly identical to setting a variable equal to a value.
The correct syntax for setting an object's properties is:

• objectName.propertyName = someValue

In this tiny example below we are creating a new mail object and setting its To and From properties.

ASP Code:
<%
Dim myObject
Set myObject = Server.CreateObject("CDO.Message")

'Then we set the To and From properties


myObject.To = "[email protected]"
myObject.From = "[email protected]"

'You must Set your objects to "nothing" to free up the


'the computer memory that was allocated to it
Set myObject = nothing
%>

Now I know we didn't DO anything in the above example, but we still need to learn a bit more about
objects before we can get anything done! Objects, besides having a clump of associated common
variables, may also have a collection of functions(which become referred to as methods) associated
with them.
These methods are processes that you would want to commonly do to either manipulate the variables
of the object or to use the variables to do something. In our Message object we have a collection of
information that, when put together into the proper email form and sent to an email service will become
an email.
All this complex code has been programmed by Microsoft employees and stored into the Message
objects Send method.

ASP Object Methods

We cannot see the code that was used to program the Send method, but that's one of the great things
about using object programming. You know what you need to know and nothing more. In our example
below we create a Message object and set the necessary properties and send it off with the Send
method.

ASP Code:
<%
Dim myObject
Set myObject = Server.CreateObject("CDO.Message")

'Then we set the To and From properties


myObject.To = "[email protected]"
myObject.From = "[email protected]"
myObject.Subject = "Can you see me?"
myObject.TextBody = "I'm really really big!"

myObject.Send()

'You must Set your objects to "nothing" to free up the


'the computer memory that was allocated to it
Set myObject = nothing
%>

Note:If you are running this on your home computer there are a slough of issues that may arise with
sending an email. Microsoft has a large FAQ about using the CDO.Message object that may help you.
Knowing Microsoft, that link may go dead soon, so Contact Us if it expires!

ASP Object Summary

In this lesson you learned how to create and destroy an object in ASP. You also learned how to
access the properties and utilize the methods of an object. If you still have no idea what this lesson
was about, hopefully there's enough information for you to hack out what you need to do in your ASP
project.

ASP DLL Information

When creating or using complex ASP web applications you will surely run into one that requires the
use of a DLL. The DLL usually includes code that was compiled in VB, C++, or other Windows
programming languages to be used in the ASP application.
Registering a DLL

Before you can start using the code that resides in the DLL file, you must first register the DLL with the
windows runtime library. There are two ways to let windows know about this new DLL.

• Save the DLL to C:\Windows\system32\

or

• Manually register it with the regsvr32 application

The first option is self-explanatory, but the second option takes a bit more work. Here is a quick How-
To on registering DLLs:

1. Find out the location of your DLL. We will be using C:\Inetpub\wwwroot\tizagASP\myDLL.dll in


this example.
2. Click on the Start menu and choose Run
3. Type in regsvr32.exe "C:\Inetpub\wwwroot\tizagASP\myDLL.dll" (With the quotes)
4. You should get a confirmation message if it succeeded, such as: "DllRegisterServer in
C:\Inetpub\wwwroot\tizagASP\myDLL.dll succeeded"

Using Your DLL in ASP

Now that you have registered your DLL you need to learn how to access the functions that are
contained within it. Let us assume for the sake of this example that the DLL file is called "myDLL.dll"
and the name of the class is "myClass".
To create an instance of this class you would use the Server.CreateObject method like so:

ASP Code:
<%
'Note this is example code, it will not work
' unless you create a myDLL, myClass, and a myMethod
Dim myObject
myObject = Server.CreateObject("myDLL.myClass")
myObject.myMethod("something")
myObject = nothing
%>

ASP ADO

This lesson will provide a brief overview of what ADO is and why it is necessary to have in your ASP
programming repertoire. ADO stands for ActiveX Data Objects. ActiveX Data Objects are a collection
of components that can be used in your ASP programs.

Accessing the Database


ADO is specifically used as means to communicate and manipulate a database. The types of
databases ADO will allow your ASP program to interact include Access, MySQL, and MSSQL to name
a few. In this lesson we will be connecting to an Access database, so you will need to have access to
Access(hehe) to complete this lesson.

Create Your Access Database

Before you can connect to the Access database you have to first create the Access database file. Fire
up your copy of MS Access and create the following database:

1. Create a New blank database called "tizag.mdb" (without the quotes) and save it to
"C:\Inetpub\wwwroot\tizagASP\" (without the quotes)
2. Use the wizard to create the database.
3. Add two fields to your table: FirstName and LastName
4. Click Next
5. Name the table "TizagTable" (without the quotes)
6. Select "Yes, set a primary key for me"
7. Click Next
8. Click Finish

Now that we have our database all that remains to connect to it.

Using ADO to Connect to an Access Database

Create an ASP file called "tizagADO.asp" and save it in the same directory as your Access database
file.
In the following ASP code we first create an ADO database connection and then we set up the
ConnectionString and finally we call the Open method with our Access database filename to finish the
opening process.

ASP Code:
<%
Dim myConn
Set myConn = Server.CreateObject("ADODB.Connection")
myConn.Open = ("DRIVER={Microsoft Access" &_
" Driver (*.mdb)};DBQ=" &_
"C:\Inetpub\wwwroot\tizagASP\tizag.mdb;")
myConn.Close()
Set myConn = nothing

QUERY STRING

The QueryString collection is used to retrieve


the variable values in the HTTP query string.
The HTTP query string is specified by the
values following the question mark (?), like
this:
<a href= "test.asp?txt=this is a query string
test">Link with a query string</a>
The line above generates a variable named txt
with the value "this is a query string test".
Query strings are also generated by form
submission, or by a user typing a query into
the address bar of the browser.

Syntax

Request.QueryString(variable)[(index)|.Count]

ParameterDescription
variable Required. The name of the variable
in the HTTP query string to retrieve
index Optional. Specifies one of multiple
values for a variable. From 1 to
Request.QueryString(variable).Count

Examples

Example 1
To loop through all the n variable values in a Query String:
The following request is sent:

http://www.w3schools.com/test/names.asp?n=John&n=Susan
and names.asp contains the following script:
<%
for i=1 to Request.QueryString("n").Count
Response.Write(Request.QueryString("n")(i) & "<br />")
next
%>
The file names.asp would display the following:
John
Susan
Example 2
The following string might be sent:
http://www.w3schools.com/test/names.asp?name=John&age=30
this results in the following QUERY_STRING value:
name=John&age=30
Now we can use the information in a script:
Hi, <%=Request.QueryString("name")%>.
Your age is <%= Request.QueryString("age")%>.
Output:
Hi, John. Your age is 30.
If you do not specify any variable values to display, like this:
Query string is: <%=Request.QueryString%>
the output would look like this:
Query string is: name=John&age=30
ASP OBJECTS in BRIEF.

Response Object
The ASP Response object is used to send
output to the user from the server. Its
collections, properties, and methods are
described below:

Collections

Collection Description
Cookies Sets a cookie value. If the cookie
does not exist, it will be created,
and take the value that is specified

Properties

Property Description
Buffer Specifies whether to buffer
the page output or not
CacheControl Sets whether a proxy server
can cache the output
generated by ASP or not
Charset Appends the name of a
character-set to the content-
type header in the Response
object
ContentType Sets the HTTP content type
for the Response object
Expires Sets how long (in minutes) a
page will be cached on a
browser before it expires
ExpiresAbsolute Sets a date and time when a
page cached on a browser
will expire
IsClientConnectedIndicates if the client has
disconnected from the server
Pics Appends a value to the PICS
label response header
Status Specifies the value of the
status line returned by the
server

Methods

Method Description
AddHeader Adds a new HTTP header and a
value to the HTTP response
AppendToLogAdds a string to the end of the
server log entry
BinaryWrite Writes data directly to the output
without any character conversion
Clear Clears any buffered HTML output
End Stops processing a script, and
returns the current result
Flush Sends buffered HTML output
immediately
Redirect Redirects the user to a different
URL
Write Writes a specified string to the
output

Request Object
When a browser asks for a page from a server,
it is called a request. The ASP Request object is
used to get information from the user. Its
collections, properties, and methods are
described below:

Collections

Collection Description
ClientCertificateContains all the field values
stored in the client certificate
Cookies Contains all the cookie values
sent in a HTTP request
Form Contains all the form (input)
values from a form that uses
the post method
QueryString Contains all the variable values
in a HTTP query string
ServerVariables Contains all the server variable
values
Properties

Property Description
TotalBytes Returns the total number of bytes
the client sent in the body of the
request

Methods

Method Description
BinaryRead Retrieves the data sent to the
server from the client as part of a
post request and stores it in a safe
array

Application Object
An application on the Web may be a group of
ASP files. The ASP files work together to
perform some purpose. The Application object
in ASP is used to tie these files together.
The Application object is used to store and
access variables from any page, just like the
Session object. The difference is that ALL users
share one Application object, while with
Sessions there is one Session object for EACH
user.
The Application object should hold information
that will be used by many pages in the
application (like database connection
information). This means that you can access
the information from any page. It also means
that you can change the information in one
place and the changes will automatically be
reflected on all pages.
The Application object's collections, methods,
and events are described below:

Collections

Collection Description
Contents Contains all the items appended
to the application through a
script command
StaticObjects Contains all the objects
appended to the application with
the HTML <object> tag

Methods

Method Description
Contents.Remove Deletes an item from the
Contents collection
Contents.RemoveAll()Deletes all items from the
Contents collection
Lock Prevents other users from
modifying the variables in
the Application object
Unlock Enables other users to
modify the variables in
the Application object
(after it has been locked
using the Lock method)

Events

Event Description
Application_OnEnd Occurs when all user
sessions are over, and the
application ends
Application_OnStartOccurs before the first new
session is created (when
the Application object is
first referenced)

Session Object
When you are working with an application, you
open it, do some changes and then you close
it. This is much like a Session. The computer
knows who you are. It knows when you start
the application and when you end. But on the
internet there is one problem: the web server
does not know who you are and what you do
because the HTTP address doesn't maintain
state.
ASP solves this problem by creating a unique
cookie for each user. The cookie is sent to the
client and it contains information that identifies
the user. This interface is called the Session
object.
The Session object is used to store information
about, or change settings for a user session.
Variables stored in the Session object hold
information about one single user, and are
available to all pages in one application.
Common information stored in session
variables are name, id, and preferences. The
server creates a new Session object for each
new user, and destroys the Session object
when the session expires.
The Session object's collections, properties,
methods, and events are described below:

Collections

Collection Description
Contents Contains all the items appended
to the session through a script
command
StaticObjects Contains all the objects
appended to the session with
the HTML <object> tag

Properties

Property Description
CodePage Specifies the character set that
will be used when displaying
dynamic content
LCID Sets or returns an integer that
specifies a location or region.
Contents like date, time, and
currency will be displayed
according to that location or
region
SessionID Returns a unique id for each
user. The unique id is generated
by the server
Timeout Sets or returns the timeout
period (in minutes) for the
Session object in this application

Methods

Method Description
Abandon Destroys a user session
Contents.Remove Deletes an item from the
Contents collection
Contents.RemoveAll()Deletes all items from the
Contents collection

Events

Event Description
Session_OnEnd Occurs when a session ends
Session_OnStartOccurs when a session starts
Server Object
The ASP Server object is used to access
properties and methods on the server. Its
properties and methods are described below:

Properties

Property Description
ScriptTimeoutSets or returns the maximum
number of seconds a script can
run before it is terminated

Methods

Method Description
CreateObject Creates an instance of an object
Execute Executes an ASP file from inside
another ASP file
GetLastError()Returns an ASPError object that
describes the error condition that
occurred
HTMLEncode Applies HTML encoding to a
specified string
MapPath Maps a specified path to a
physical path
Transfer Sends (transfers) all the
information created in one ASP
file to a second ASP file
URLEncode Applies URL encoding rules to a
specified string

The ASPError Object


The ASPError object was implemented in ASP
3.0 and is available in IIS5 and later.
The ASPError object is used to display detailed
information of any error that occurs in scripts
in an ASP page. The ASPError object is created
when Server.GetLastError is called, so the error
information can only be accessed by using the
Server.GetLastError method.
The ASPError object's properties are described
below (all properties are read-only):
Note: The properties below can only be
accessed through the Server.GetLastError()
method.

Properties

Property Description
ASPCode Returns an error code generated
by IIS
ASPDescriptionReturns a detailed description of
the error (if the error is ASP-
related)
Category Returns the source of the error
(was the error generated by
ASP? By a scripting language?
By an object?)
Column Returns the column position
within the file that generated
the error
Returns a short description of
Description
the error
File Returns the name of the ASP file
that generated the error
Line Returns the line number where
the error was detected
Number Returns the standard COM error
code for the error
Source Returns the actual source code
of the line where the error
occurred

You might also like