Wednesday, 30 November 2011

OPEN NEW WINDOW WITH HYPERLINK

This JavaScript will open a new browser window when you click on the hyperlink. You can also change the optional settings you want depending on how you want the new window to display in the browser. 1 = Yes and 0 = No for displaying purposes.




ASP Web Pro







Open New Window




http://www.aspwebpro.com/javascripts/windows/opennewwithhyperlink.asp

OPEN NEW WINDOW AUTOMATICALLY

This JavaScript will open a new browser window automatically when your web page is accessed. You can also change the optional settings you want depending on how you want the new window to display in the browser. 1 = Yes and 0 = No for displaying purposes.




ASP Web Pro







Open New Window




http://www.aspwebpro.com/javascripts/windows/opennewautomatic.asp

TEXT ROLLOVER

This JavaScript displays a simple text rollover like the ones you see on our main menu:




ASP Web Pro






Your Text Here




http://www.aspwebpro.com/javascripts/rollovers/textcolor.asp

DISBALE RIGHT-CLICK

If you want to deter users from copying the content from your website, this script will disable the right-click function on the users mouse. Of course, we say this is only a deterant because the user can change the settings in their browser and get around this. At least it helps to deter novices from stealing your work.


ASP Web Pro










http://www.aspwebpro.com/javascripts/miscellaneous/disablerightclick.asp

PAGE BREAK

It is often necessary to insert page breaks into your web pages so that users can print your information without data or images running off of one page to another. Using this simple JavaScript, "Page data 1" will print on page 1 and "Page data 2" will print on page 2.


ASP Web Pro




Page data 1


Page data 2





http://www.aspwebpro.com/javascripts/miscellaneous/pagebreak.asp

PRINT THIS PAGE

There are a lot of websites that contain information that users want to print. If you have a page that is printer friendly, why not include a print button or link for the user. Just paste the below code into your page where you want your print option to appear.


ASP Web Pro









http://www.aspwebpro.com/javascripts/miscellaneous/printthispage.asp

CLOSE WINDOW

Many websites use popup windows that display while you are surfing their website. They are very commonly used for displaying advertisements. They are also often used for site Help files, short surveys, and a few other things. Well, if you are going to use a popup window on your website, it is proper netiquette to include a close window button or link within the popup window. All you have to do is choose if you want to display a close window button or link and paste the one line of code below into your page. It just doesn't get any easier than that!


ASP Web Pro





or Close Window





http://www.aspwebpro.com/javascripts/miscellaneous/closewindow.asp

MAKE THIS MY HOME PAGE

We all want as much traffic to our website as possible. Well, if people have your website set as their homepage that will guarantee you at least some traffic each time they connect to the Internet, so why not make it easy for your users to do this by adding a button to your page like this:

* Note: This script only works for IE 5.0 +


ASP Web Pro









http://www.aspwebpro.com/javascripts/miscellaneous/makethishomepage.asp

BOOKMARK THIS PAGE

We all want people to bookmark our website, so why not make it a little easier for people to do it. This short script will add your website to the users Bookmark or My Favorites list. To add this feature, just paste the code below into your page where ever you want the Bookmark link to appear.


ASP Web Pro







http://www.aspwebpro.com/javascripts/miscellaneous/bookmarkthispage.asp

ANIMATED STATUS BAR MESSAGE

This JavaScript displays an Animated Status Bar Message:




ASP Web Pro









http://www.aspwebpro.com/javascripts/messages/animated.asp

ROLLOVER HYPERLINK STATUS BAR MESSAGE

This JavaScript displays a simple text rollover like the ones you see on our main menu:




ASP Web Pro





YOUR LINK TEXT HERE




http://www.aspwebpro.com/javascripts/messages/onhyperlinkrollover.asp

ON PAGE LOAD STATUS BAR MESSAGE

This JavaScript displays the Status Bar Message you see at the bottom left of your screen:




ASP Web Pro






http://www.aspwebpro.com/javascripts/messages/onpageload.asp

START CURSOR AT FIELD

This handy little JavaScript goes inside the body tag and automatically starts the users cursor in a given form field. This script will start the cursor in the Username field:




ASP Web Pro




Please enter you Username and Password:

Username:
Password:





http://www.aspwebpro.com/javascripts/forms/startcursoratfield.asp

DROP DOWN MENU VALIDATION

This JavaScript requires the user to select any item from the drop down menu except the first entry:




ASP Web Pro





Please choose an item from the drop down menu:

Choose a username:





http://www.aspwebpro.com/javascripts/forms/dropdownvalidation.asp

BLANK FIELD VALIDATION

This JavaScript ensures that the user enters a value into your form fields before allowing them to submit the form:




ASP Web Pro


http://www.aspwebpro.com/javascripts/forms/blankfieldvalidation.asp

DATE / TIME ON STATUS BAR

This script will display the current day of the week, month, date, year, hour, minutes, seconds, and AM or PM in your Status Bar like this:

Thursday, May 10, 2001 10:45:01 AM


ASP Web Pro







The rest of your page.




http://www.aspwebpro.com/javascripts/dates/datetimeonstatusbar.asp

TIME

This handy little script displays the time with the hour, minutes, seconds, and AM or PM like this:

11:36:09 AM


ASP Web Pro













http://www.aspwebpro.com/javascripts/dates/time.asp

COUNT DOWN TO DATE

This script performs a count down to any any date you plug in. You can customize as many different messages as you like. Here is how the script will display like this:

It'sNew Years Day 2010!!


ASP Web Pro









http://www.aspwebpro.com/javascripts/dates/countdowntodate.asp

MONTH / DAY / YEAR

This script displays the date in this format:

November 30, 2011


ASP Web Pro








http://www.aspwebpro.com/javascripts/dates/monthdayyear.asp

SPECIAL CHARACTERS

When you use Active Server Pages, there are many special characters that you need to be aware of. Here is a list and description of the most common:

'

The single quotation mark signifies a comment within ASP code. Comments are generally used for organizational purposes in web design so that webmasters can share work easily and check for bugs in their system

&

The ampersand symbol is a concatenation operator that is used to combine two expressions into a string result. Here is an example from our ASPEmail script:
Mail.Body = "Email: " & strEmail & vbCrLf & "Name: " & strName

_

The underscore signifies that a one single piece of code is being written on more than one line. In ASP, many portions of code are designed to be written on one single line. If the line becomes too long and runs off the page, you can simple enter an underscore at the end of the line, return to the next line, and then continue writing your code. Although the code is written on more than one line, it will still function as one line of code.

vbCrLf

vbCrLf simply returns to the next line. This is most commonly used when displaying data such as in an email message. If you have two form fields that you want to display on separate lines in an email, simply add a vbCrLf between their code in your ASP page.

http://www.aspwebpro.com/tutorials/asp/specialcharacters.asp

INTERVAL VALUES FOR DATES / TIMES

When you work with dates and times, it is vital to know the correct value that represents the date or time period you are wanting. Here is a list of available date / time values:
Value
Meaning
"yyyy"
Year
"q"
Quarter
"m"
Month
"y"
Day of Year
"d"
Day
"w"
Weekday
"ww"
Week of Year
"h"
Hour
"n"
Minute
"s"
Seconds

Here is an example of how this may be used:

<% Response.Write DateAdd ("d", 1, Date) %>

This displays tomorrows date like this: 01/12/2011

http://www.aspwebpro.com/tutorials/asp/intervalvaluesfordates.asp

INCLUDE FILES

If you are getting into web development, especially with ASP programming, include files are going to become one of your best friends. In essence, an include file allows you to write an ASP script one time and then include it in multiple web pages without having to rewrite all the code.

So when and how do you do this? One of the most basic examples is placing your database connection within an include statement and then using a simple include statement to include your connection string in your web pages.

First, you create a folder named /includes within your root directory.

Next, you create a new file named connection.asp and save it within your new /includes folder.

All that is left is to input a simple one line include statement into each page where you need to have a database connection. Here is how the include statement looks:




The include statement cannot be placed inside of your <% %>. If you need to place an include statement within your ASP code, you need to close your ASP code, input the include statement, and reopen your ASP code like this:
<% ' ASP code here %>

<% ' ASP code here %>

OK, you've got that. Now what is the advantage of using an include file like this? Well, think about it. Let's say your website is 100 pages and that 6 months from now something is your database conenction chages. Rather than having to go through and edit your connection string in all 100 pages, you can simply edit it one time in your include file and that will automatically update it throughout your website.

There are two way of including files in a web page. You can use INCLUDE VIRTUAL or INCLUDE FILE. Our preference is to use INCLUDE VIRTUAL. This means that you can just enter the virtual path of your website to the file you want to include. In the example of the path is "/includes/connection.asp".

http://www.aspwebpro.com/tutorials/asp/includefiles.asp

GLOBAL.ASA

The global.asa file is a special file that handles session and application events. This file must be spelled exactly as it is here on this page and it must be located in your websites root driectory. This is a very useful file and can be used to accomplish a variety of tasks.

For example, we use the global.asa file on this website to display the number of Active Users on our site. Rather than inputting data into a database and keeping a stored record of it, our global.asa file acts as a monitor of how many users are visiting any page our website. There are no records stored in any database or text file, the information just flows in and out. Take a look at the code below we use to do this:



What the global.asa file does is create a session for each new user that is actively surfing any part of our website. Then, the session will time out or end either when the user leaves our website or at the default setting of 20 minutes.

There are several other things you can use the global.asa file for, but this tutorial was just intended to show you what makes this file special and to give you an idea of what it is used for

http://www.aspwebpro.com/tutorials/asp/globalasa.asp

PASS VARIABLES WITH QUERYSTRING

Ok, so you want to pass variables between your web pages with the using the QueryString method or the URL bar for you folks still learning ASP lingo. Well, it's as easy as it is passing variables using the form method. One of the most simple and popular ways of passing variables using the querystring method is by using a basic hyperlink.

Let's keep things simple and say that you sell books and movies on your website. Rather than creating a books.asp page and a movies.asp page to list your available products, you can put all your products into a database and display them all on one page accoring to what the user wants to see. So how do we do this?

The first thing you need to do is create your home.asp page and paste the code below into your page:


Home Page


Choose a product category to view our products:

Books
or
Movies



Notice that both links point to the same products.asp page. However, they each have a variable attached to the link with a different value. When you click on the Books link, you will see the variable and its respective value displayed in your URL bar like this: http://www.yoursite.com/products.asp?Products=Books

Now, how do get this to display your books on your products.asp page? It's a little more complicated so take it slow.

The next step is to create your products.asp page and paste the following code:

<% DIM strProducts strProducts = Request.QueryString("Products") %>


Products Page


<% IF strProducts = "Books" THEN ' Display books here ELSE ' Display movies here END IF %>,

Thank you for contacting us. We have received your message and will send a reply to your email address, <% Response.Write strEmail %>, as soon as possible.




That's all there is to it. Now, you can pass variables from one page to another using the QueryString method. If you are eager to learn more about how to actually display data from your database on your page, be sure to check out our Displaying Data From Database Tutorial.

If you want to learn another way to pass variables between pages, be sure to check out our Passing Variables with Form Tutorial.

http://www.aspwebpro.com/tutorials/asp/passvariableswqs.asp

PASS VARIABLES WITH FORM

Ok, so you want to pass variables between your web pages. Good news, it's a piece of cake with ASP. As with just about everything else in ASP, there are many ways to do this. In this tutorial, we will show you how to pass variables from one page to another using a simple form.

Let's say you have a contact form on your website and you want to personalize the confirmation page for the user. The first thing you need to do is create a contact.asp page and paste the code below into your page:


Contact Us


Email
First Name:
Last Name:
Subject:
Comments:




Now, you've got your basic form. Simple enough, right? Next, create a contactconfirm.asp page and paste the code below:

<% DIM strEmail, strFirstName, strLastName, strSubject strEmail = Request.Form("Email") strFirstName = Request.Form("FirstName") strLastName = Request.Form("LastName") strSubject = Request.Form("Subject") %>


Confirmation


<% Response.Write strFirstName %>,

Thank you for contacting us. We have received your message and will send a reply to your email address, <% Response.Write strEmail %>, as soon as possible.




This is a nice way to personalize the users experience by displaying the first name and email address that they entered on the form page.

When passing variables with a form, the Request.Form initiates the request for the form data and the ("Email") specifies the form field we are requesting. In this case, we created our own variables: strEmail, strFirstName, etc and set their values equal to the data from their respective form field. Rather than creating your own variables and setting each of their values, you could simply place <% Request.Form("Email") %> directly in your confirmation page instead of the <% Response.Write strEmail %>. Again, this is a matter of personal preference. However, we recommend you use the variable technique, especially when you start dealing with more complex ASP pages.

Now, you can pass variables from page to page within your website. Piece of cake!

f you want to learn another way to pass variables between pages, be sure to check out our Passing Variables with QueryString Tutorial.

http://www.aspwebpro.com/tutorials/asp/passvariableswform.asp

NEW WAY TO HANDLE VARIABLES

The EASIEST way to deal with variables!!

Allow me to introduce myself.

My name is Rob Collyer, I lay eyes upon ASP years ago and have been heavily coding since.
It always struck me as a complete pain in the neck the way in which we have all been dealing with variables in ASP, for as long as we have used ASP.

What do I mean? ........ Allow me to explain with this example of the hard way:-

<% FirstName = Request.Form("FirstName") Surname = Request.Form("Surname") Address1 = Request.Form("Address1") Address2 = Request.Fomr(Address2") ... ... %>

Rather than go on longer than necessary into yet more lines looking exactly the same as the ones above, to put my point across, I'll put you out of your misery.

Why do variables have to be this TEDIOUS to deal with??? I wanted a way to read in all variables at once in one go, with just one function call.... I must be mad.... sure enough, I was told this as well as things like 'It's not possible', etc.

Sure enough, at the time, it wasn't possible. To my rescue came Microsoft, with Version 5 of the VBScript engine and a new command called Execute. Execute(string) basically executes a string as though it were ASP.. So Execute("Response.write ""Hello"") .... would have the same effect as just using response.write "hello"

As soon as I saw this new feature I knew instantly what I could do with it:-

<% For Each Field in Request.Form TheString = Field & "= Request.Form(""" & Field & """)" Execute(TheString) Next %>

We are setting variables automatically. That one little tiny piece of code, has saved me so much time over the last year, you will not believe.
Ok, it does have it flaws, Forms with image submit buttons pass form variable names like "submit.X", and "submit.Y" (Co-ordinates where you clicked on the submit image) which obviously wont do for variable names in ASP, and results in the white error page from hell.... But we can start to prevent these things:-

<% For Each Field in Request.Form tmpField = Replace(Field,".","") 'remove full stops TheString = tmpField & "= Request.Form(""" & Field & """)" Execute(TheString) Next %>

Why stop there?? There are many silly characters that are fine in HTML controls as names, but when setting variable names automatically like this in VBScript, these characters will not do. You can easily add additional lines as above to escape other characters like spaces, hyphens and all manner of other ones too.

You've got multiple controls on forms.... how are you gonna assign variables to multiple select boxes?
As a developer, I found it handy to read these 'multiple' part form variables into an array... I will build upon the above code to handle multiple items and create arrays from them:-

<% For Each Field in Request.Form tmpField = Replace(Field,".","") 'remove full stops ItemCount=Request.Form(Field).count IF ItemCount > 1 then
execute "redim " & field & "(" & itemcount -1 & ")" 'Dynamically dimension the array
For Item = 0 To ItemCount - 1
TheString = tmpField & "("&Item&")= request.form(""" & field & """).item(" & Item + 1& ")"
Next
Else
TheString = tmpField & "= Request.Form(""" & Field & """)"
End If
Execute(TheString)
Next
%>

I hope by now you can see the potential of what all of the above means to you as the developer.....
I urge you all to write your own functions that'll handle variables the way you want them to, and please remember.... FORMS were just an example, don't stop there, after all there are Querystrings, Cookies, Session variables, Application Variables, ServerVariables. Then there are recordsets (why not?) and the dictionary objects, etc, etc, etc.

Just remember, you are now armed with info which will save you a great deal of time, why not get busy writing some variable handling functions of your own??

If anybody wants a function to selectively handle Form, Querystring, Cookies, Session, Application and Server variables then I have one...just mail me. It also has a parameter to run in DEBUG mode which will show you variables in all objects, their values and whether their names present a problem during conversion. It'll also flag those controls that can be set to arrays, etc.

Anyway, those that do feel inspired to get writing their own handlers, let me ask one thing.... Send me a copy of your finished function(s), this is pretty new stuff and I'm well open to being inspired by YOUR code.

Feel free to contact me with your feedback.

Enjoy!
http://www.aspwebpro.com/tutorials/asp/newwaytohandlevar.asp

DISPLAY DATA FROM DATABASE

Alright, you have your database connection established and now you want to display data from your database on your page. Easy enough. We'll take the same code that we left off with from our Open Database Connection Tutorial except we will change the database table name to myCustomers and build from there.

First, create a database with a table called myCustomers with the following fields and add some data:
Company - text field
Address - text field
City - text field
State - text field
Zipcode - number field

As a reminder, here is our open database connection code:

<% DIM objConn Set objConn = Server.CreateObject("ADODB.Connection") objConn.ConnectionString = "DSN=myCONNECTION.dsn" objConn.Open DIM mySQL mySQL = "SELECT * FROM myCustomers" DIM objRS Set objRS = Server.CreateObject("ADODB.Recordset") objRS.Open mySQL, objConn %>

ASP Web Pro

Display data from database here.


Now, if you know that you only have one customer in your database to display, it is very simple. Just paste the below code into the body section of your page:



<% Response.Write objRS("Company") %>
<% Response.Write objRS("Address") %>
<% Response.Write objRS("City") %>
<% Response.Write objRS("State") %>
<% Response.Write objRS("Zipcode") %>



<% ' Don't forget to close your connection after you display your data. objRS.Close Set objRS = Nothing objConn.Close Set objConn = Nothing %>

This will neatly display your customer's data on your page.
When displaying data from a database on your pages, it is a good idea to use tables to organize how the data will be displayed.

Now, ideally you will have more than one customer. If have multiple customers in your database, you need to do a little bit more



<% DO WHILE NOT objRS.EOF %> <% objRS.MoveNext Loop %>
<% Response.Write objRS("Company") %>
<% Response.Write objRS("Address") %>
<% Response.Write objRS("City") %>
<% Response.Write objRS("State") %>
<% Response.Write objRS("Zipcode") %>




<% ' Don't forget to close your connection after you display your data. objRS.Close Set objRS = Nothing objConn.Close Set objConn = Nothing %>

In the first example, our page displays the first and only record returned by our mySQL statement. In this example, the <% DO WHILE NOT objRS.EOF %> and <% objRS.MoveNext...Loop %> code instructs our page to display the first record returned by our mySQL statement, move to the next record, and loop back and continue the table and display the next record until there are no more records left.

So what happens if you have 100 customers and it is just too much information to display on one page? You would probably just want to display the first 10 or 20 records on your page and include a next and previous link at the bottom so that you can scroll through your records more easily. We will get into that later, but for now we will let you absorb this. Congrats!

SEARCH ENGINES

Search Engines are a vital tool on the Internet. They provide web surfers with a way to find what they are looking for. Some of the most popular Search Engines are Excite, GoTo, Lycos, and MSN. There are literally 1,000's more of them, but they all serve the same purpose for the most part.

In order to use a Search Engine, all you do is type in a single keyword or phrase, click search and voila, you have a list of related web sites. Depending on your keyword and which particular search engine you use, you could have anywhere from 10 to 10,000,000 web sites in your results. Ok, you probably already knew that much. The real question is how do I get my web site to show up in those results and show up within the top 10 results. Well, as in many things in life, it all depends.

The first thing you need is a good web site. The second thing you need is to have an effective set of keyword and description META tags in your home page. These META tags must appear in this format:




and they must be located within the tags of your home page. Your keywords can either be a single word or a phrase and must be separated with a comma like this "asp, active server pages". Your description is a brief and to the point description of your web site.
Many Search Engines have advanced tools that rank your web site according to keyword relevance. In order for your keywords to be considered relevant, they should be used in your description META tag and also within the text of your home page. As a general rule, your keywords should appear at least 3 times within the text of your home page in order for them to be considered relevant. Be careful, though. If your keywords appear more than 8 times on your page, it may be considered spam by search engines and be banned from their listing service all together.

Now, you have your web site and your META tags. What next? Well, now you need to submit your web site to the search engines. You can do this manually on your own each month, which could potentially take hours of your own time or you can use a low cost search engine submission service like our SubmitME! program.

When you submit your web site to the major search engines, you want to use keywords that are as specific as possible. The reason for this is that search engines are big business these days. They charge literally $1,000's of dollars per month to huge corporations that want their web sites listed at the top of a given category and if you have a small business or personal web site, you simply cannot compete with that. For example, let's say you have a car dealership web site and you use "cars, trucks, sports utility vehicle" as your keywords. When a web surfer searches for the term cars, they will get a long list of car manufacturers like Chrysler, Ford, and Toyota. They will also get a long list of car rental companies like Avis, Budget, and Hertz because those companies are paying the top dollar to be listed first. You probably would not find your listing until about 300 sites later if you are lucky. Once you get past the top paying companies, most search engines list smaller web sites in random order so there is really not much you can do about that. Sometimes you may be listed within the top 100 and sometimes it will be the top 100,000. Sure, there are a couple of tricks that you can try that may help a little bit, but unless you are ready and willing to pay for it, you are better off looking for other options.

So how do we solve this dilemma? Narrow down your keywords. Instead of just using keywords like these: "cars, trucks, sports utility vehicle" try using specific brands or names like these: "Ford Bronco, Toyota Corolla" or narrow it down geographically like this: "Charlotte NC car dealerships, NC Ford dealerships", etc.

What else can I do? Nowadays, there are lots of smaller industry specific directories and search engines you can use. For example, if you are a manufacturing company, you can list your web site with the Thomas Register Directory of Manufacturers. There are also lots of geographically oriented search engines like www.uk.goto.com for the United Kingdom.

Search engines are a necessity for the survival of the Internet and its web sites in general. If you do not list your web site with search engines, the only people can find your site is either by word of mouth or by accident. That's a tough way to grow your web site, so get your web site and META tags together and start submitting!

http://www.aspwebpro.com/tutorials/internet/searchengines.asp

SQL ADVANCED

OK, so you got through our SQL Basics Tutorial. Now, we are moving on to some more advanced SQL statements. As a refresher, here is our standard connection and recordset information, which shows you where your SQL will go.

<% DIM objConn Set objConn = Server.CreateObject("ADODB.Connection") objConn.ConnectionString = "DSN=myCONNECTION.dsn" objConn.Open DIM mySQL mySQL = "SELECT * FROM myTABLE" DIM objRS Set objRS = Server.CreateObject("ADODB.Recordset") objRS.Open mySQL, objConn %>



Display data from database here.


Now, let's get to the good stuff. Here are some of the more advanced things you can do with your SQL statements.

mySQL = "SELECT Count(*) AS intTotal FROM tblInvoices"

This example counts the number of records contained in our intInvoices table.

mySQL = "SELECT SUM(Revenue) AS intTotal FROM tblInvoices"

This example sums a currency field called revenue from our intInvoices table. There are other commands you can use other than SUM in the same way. You can also replace SUM with AVG, MIN, or MAX to find the average, minimum, or maximum values. If you are really into statistical analysis, you can even use VARIANCE or STDDEV to return the variance or standard deviation values.

mySQL = "SELECT * FROM tblInvoices WHERE DueDate = # " & Date() & " # "

This example selects all of the records in our tblInvoices tables where the DueDate field equals todays date.

mySQL = "SELECT * FROM tblInvoices WHERE Type = ' " & strVariable & " ' "

This example selects all of the records in our tblInvoices tables where the Type field is equal to a string or text variable such as "Customer" that is entered on your ASP page.

mySQL = "SELECT * FROM tblInvoices WHERE Number = " & intVariable & " "

This example selects all of the records in our tblInvoices tables where the Number field is equal to an integer or numeric variable such as "100" that is entered on your ASP page.

These are only some of the more advanced SQL statements. We are still only scratching the surface here, but we will continue to add more advanced SQL statements to this page as time goes on so be sure to check back.

http://www.aspwebpro.com/tutorials/asp/sqladvanced.asp

SQL BASICS

SQL stands for Structured Query Language and it is the primary tool for selecting data from databases. If you are selecting data directly from a database and not via an ASP web page, there are many different versions of SQL. For example, MS SQL Server uses its own version of SQL called Transact SQL and MS Access also uses a less modified version of SQL.

With that said, we are here to learn how to use SQL within an ASP page. So once again, we will start with the code from our Database Connection Tutorial.

<% DIM objConn Set objConn = Server.CreateObject("ADODB.Connection") objConn.ConnectionString = "DSN=myCONNECTION.dsn" objConn.Open DIM mySQL mySQL = "SELECT * FROM myTABLE" DIM objRS Set objRS = Server.CreateObject("ADODB.Recordset") objRS.Open mySQL, objConn %>



Display data from database here.


Anytime you want to display a specific subset of data from your database onto a web page, you need to use a SQL statement. The example above show a basic SQL statement.

First, just like with the connection and recordset objects you must create a variable. In this case, we chose mySQL. Then, you write your statement. In SQL, SELECT and FROM are constants. The * is a wildcard meaning ALL as in SELECT ALL FROM. Last, myTABLE is the name of the table in your database where the records should be selected from.

Now, there are a lot of extra things you can include in a SQL statement to be more particular about records to display and even how to display them. Here are a few examples.

mySQL = "SELECT * FROM tblUsers ORDER BY DateVisited DESC"

This example includes a date field called DateVisited and would display records on your web page according to date with the most recent listed first.

mySQL = "SELECT TOP 10 * FROM tblUsers ORDER BY DateVisited DESC"

This example would display the top 10 records in your database according to date.

mySQL = "SELECT * FROM tblUsers WHERE Type = ' Customer ' "

This example includes a field called Type and would display all of your records that have Customer listed as a type.

mySQL = "SELECT * FROM tblUsers WHERE DateVisited BETWEEN 1/1/01 AND 12/31/01"

This example would display all of your records where the date contained in the DateVisited field is between 1/1/01 and 12/31/01.

mySQL = "SELECT * FROM tblInvoices WHERE Customer LIKE ' M% ' "

This example selects all of the records from our intInvoices table where the Customer field begins with the letter M.

mySQL = "SELECT * FROM tblInvoices WHERE Customer LIKE ' _icrosoft ' "

This example selects all of the records from our intInvoices table where the Customer field ends with the letters icrosoft.

mySQL = "SELECT * FROM tblInvoices WHERE Customer LIKE ' [ m - o ]icrosoft ' "

This example selects all of the records from our intInvoices table where the Customer field begins with any letter between m and o and also ends with the letters icrosoft.

These are some of the basics for writing SQL statements. There are a lot more, but this will help get you started. Later on we will be adding an advanced SQL Advanced Tutorial.

http://www.aspwebpro.com/tutorials/asp/sqlbasics.asp

FORMS

Forms are one of the most important tools on a web site because they allow your web users to communicate easily with you. It is also a valuable way for you to obtain information from your web users.

Here is the code for a simple form:


ASP Web Pro



Email:
Namel:






This form would display like this:
Email:
Name:

The tags work just like any other HTML tag. Anytime you open a form with you must close it with a
. Notice that
tag has its own attributes. The NAME attribute is used to assign a name to the form. The METHOD attribute is how the form data will be sent. There are only two types of Methods available, POST or GET. Unless you are a more advanced HTML'er, stick with the POST method. This is what the large majority of web forms use. The ACTION attirbute tells the form which page to go to next after the form is submitted.

Each form field begins with INPUT TYPE which specifies what type of field it is. In this case "text" means it is a basic text field that can hold any kind of data. Notice that each form field also has its own NAME attribute to make each field unique. The SIZE attribute is optional for form field. This specifies the number of characters that can fit in a form field before it begins scrolling over and hiding characters. Finally, the submit button is represented by INPUT TYPE="submit". HTML always recognizes this as a standard submit button. The submit button also has a NAME attribute and has an additional VALUE attribute, which declares what value to display on the submit button.

Ok, you understand how to put together a simple form. Now, you want to add some advanced form elements to it. Like just about everything else in web development, you can customize your forms just about anyway you want. Here are some examples of advanced form elements:
To insert a dropdown list field, you could add this code to your form:




To insert a multi-line memo field, you could add this code to your form:









There you have it. Now, you are ready to start building and customizing your very own tables!

http://www.aspwebpro.com/tutorials/html/forms.asp

TABLES

Tables lay the groundwork for most web sites. The majority of web sites designed today are completely contained within tables. You need not look any further than this very web site for an example of this. Everything you see on this screen is contained within a table. Some of the content you see is inside of tables which are inside of other tables, this is called Nesting.

So why would you want to put the content of a web page into a table? The reason is that it is the simplest and most effective way to organize a web page. For example, how would you make two columns of text on a web page if you did not use a table? Think about it. Unless you are an advnaced HTML'er and know how to use layers, you can's do it. What you would do is create a table with two columns and then place your text in each column. Here is the code that you would need to accomplish this:


ASP Web Pro



Column 1 Text Here Column 2 Text Here




This table would display like this:

Column 1 Text Here Column 2 Text Here

The tags work just like any other HTML tag. Anytime you open a table with
you must close it with a
. The tag stands for Table Row. A table can have as many rows as you want it to. If you create a table with 3 rows and later decide that you want to add another row, just go back into your HTML source code and add another set of tags. The tag means Table Column, but technically stands for Table Data. Similarly to table rows, you can also have as many table columns as you would like. Simply add 1 set of tags for each column you would like to have in your table.
Be sure to note that your tags must always be nested inside of your tags and your tags must always be nested inside of your
tags.

Ok, so now you understand how to make a simple table. Now, you want to know how to add attributes to. You can add various attributes to your tables with some very simple code. Here are some examples:

To specify a length, you could add this to your code:
- sets the length as a percentage of the entire page
- sets the length in pixels
- sets the length as a percentage of the entire table
- sets the length in pixels

To specify a table border thickness and color, you could add this to your code:
To add a background color, you could add this to your code:
- sets the background color of the whole table
- sets the background color of a specific table cell

To add a background image, you could add this to your code:
- sets the background image of the whole table
- sets the background image of a specific table cell

There you have it. Now, you are ready to start building and customizing your very own tables!

http://www.aspwebpro.com/tutorials/html/tables.asp

META TAGS

META tags are a small, but crucial part of every web site on the Internet. In essence, META tags provide information about your web site or web page to the Internet. Think about it like this. When you look through a TV Guide, you see titles of programs and sometimes a brief description about it. Then, it is up to you to select a program to watch. Well, META tag are the TV Guide of the Internet. They give you the title, description, and much more of web sites and then it is up to you to select a web site to visit.

There are several different types of META tags. The most common META tags are:



The keywords META tag is a listing of words or phrases about the web site. The description META is a brief and to the point desciption about the web site. This is not a place for you avid writers our there to begin writing your version of the Great American Novel ; ).
A good rule of thumb is to choose between 5 - 7 keywords to describe your web site and list them in the order of importance. It is also a good idea to keep your description to under 255 characters in length. Some search engines will completely skip over your description tag if it is longer than this.

The keywords and description META tags are discussed further in our Search Engines tutorial.

Some other types of META tags are:




The HTTP-EQUIV is a standard META tag that appears in every web page and tells what type of document is being displayed. The title META tells the title of the page and the author META tag tells who authored the page.

Always remember that no matter how well you designed your web site, it will never get the attention and repeat web traffic it so richly deserves without an effective and well formed set of META tags!

http://www.aspwebpro.com/tutorials/html/metatags.asp

CLOSE DATABASE CONNECTION

A common problem among hosting companies is that ASP websites do not close the database connections after they are opened. This is a basic step that you should consider to be part of mandatory code. If you do not close your database connections, many problems can occur like web pages hanging, slow page loads, and more.

Think of it as going through a door to your house. Maybe the door will shut by itself, but maybe it won't. If it doesn't shut, who knows what will happen. If you live in the country, a bear could walk in. If you live in the city, a mugger could walk in. Alright, well maybe leaving a database connection open won't lead to anything that bad, but it will lead to a lot of unecessary headaches for both you and your hosting company.

So how do I close my database connection? It's very simple. Here is the code from our Open Database Connections Tutorial:

<% DIM objConn Set objConn = Server.CreateObject("ADODB.Connection") objConn.ConnectionString = "DSN=myCONNECTION.dsn" objConn.Open DIM mySQL, objRS mySQL = "SELECT * FROM myTABLE" Set objRS = Server.CreateObject("ADODB.Recordset") objRS.Open mySQL, objConn %>

Display data from database here.

<% objRS.Close Set objRS = Nothing objConn.Close Set objConn = Nothing %>

All you have to do is include the "objRS.Close...objConn.Close..." code from the bottom of this example anywhere on your web page after your data is displayed. Yes, it is necessary to close both the connection and the recordset. Be careful not to include your close connection code on the page before where your data is being displayed or guess what happens? That's right, the connection gets closed before the data can be displayed and you get lots of errors.

Well, that's it. Now, you know how to properly close a database connection. Be sure to include this in your ASP coding routine and it will be smoother sailing for both you and your hosting company or server administrator.

http://www.aspwebpro.com/tutorials/asp/dbconnectionclose.asp

OPEN DATABASE CONNECTION

The most basic purpose of ASP is to allow a website to connect to a database and show "Live data". It is called live data because ideally the database administrator will be updating the database routinely which will therefore automatically update the website.

So how do you do it? Well, it's actually pretty simple. First, you need to understand that there are two ways to connect to a database. You can use a DSN or DSN-less connection, both accomplish the same thing. A DSN is a Data Source Name that is setup on the server. You can think of it as a shortcut to your database because it contains the driver and database path information to your database. If you have your website hosted by an outside company like most people do, you will need to contact them directly and ask them to setup the DSN for you. You will have to tell them where your database is located within your website and you will have to give the DSN a name.
Not all hosting companies support ASP. If you are looking for a reliable hosting company for your ASP website, we recommend using ASPWebHosting.com.

Here is an example of a DSN connection:

<% DIM objConn Set objConn = Server.CreateObject("ADODB.Connection") objConn.ConnectionString = "DSN=myCONNECTION.dsn" objConn.Open %>

For those of you not familiar, we will run through the lingo. In the first section, the DIM line declares the variable objConn. The "Set objConn..." sets the connection object. "objConn.ConnectionString..." sets the connectionstring and the DSN and the last line "objConn.Open" opens the connection.

Personnally, we prefer to use DSN-less connections to our databases. The reason is that for maintenance and updating purposes, it is easier to make changes to database connections on your own rather than having to call or email your hosting company and wait for them to update your DSN.

There is a little more code involved with DSN-less connections, but it is worth it. Here is an example of a DSN-less connection:

<% DIM objConn Set objConn = Server.CreateObject("ADODB.Connection") objConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _ Server.MapPath ("/mydatabase.mdb") & ";" objConn.Open %>

The only difference between this example and the DSN example above is in the "objConn.ConnectionString = ..." line. Instead of using "DSN = myCONNECTION.dsn" you actually write out the appropriate driver and the respective path to the database. Ideally, the connection string should all be written on one line, but for display purposes we put it on two. When you paste this to your code, just remove the _ at the end of the line and put the Server.MapPath on the same line.
For maintenance purposes, we recommend that you place your database connection in a separate file like /includes/connection.asp. Then, simply use an include statement like this:

to include your connection string in your pages. Then, if your database connection should ever change, you only have to edit it one time in your connection.asp file and it updates your connection throughout your website.

http://www.aspwebpro.com/tutorials/asp/dbconnectionopen.asp

TIME AND DATE FUNCTIONS

Time and date functions allow you to customize your web pages in many different ways. Here are some of the most commonly used time and date functions:

DateValue

strResult = DateValue("September 30, 1970")

The DateValue function converts an expression into a date subtype. In this example, it returns the value "9/30/1970".

Day

strResult = Day("9/30/1970")

The Day function extracts the day value from a date expression. In this example, it returns the value "30".

Weekday

strResult = Weekday("9/30/1970")

The Weekday function extracts the day value from a date expression. In this example, it returns the value "4".

Month

strResult = Month("9/30/1970")

The Month function extracts the day value from a date expression. In this example, it returns the value "9".

Year

strResult = Year("9/30/1970")

The Year function extracts the day value from a date expression. In this example, it returns the value "1970"

Now

strResult = Now

The Now function returns the current date and time according to the current setting of the computer or server. In this example, it returns the value " 30/11/2011 07:59:42 ".

Time

strResult = Time

The Time function returns the current time according to the current settings. In this example, it returns the value " 07:59:42 ".

Hour

strResult = Hour(Now)

The Hour function returns the current time according to the current settings. In this example, it returns the value " 7 ".

Minute

strResult = Minute(Now)

The Minute function returns the current time according to the current settings. In this example, it returns the value " 59

Second

strResult = Second(Now)

The Second function returns the current time according to the current settings. In this example, it returns the value " 42 "

http://www.aspwebpro.com/aspscripts/functions/timedate.asp

STRING FUNCTIONS

String functions are a great way to manipulate and parse the data within your strings, below are some of the most commonly used ones. For our purposes, we will use this variable as an example:

strExample = "These are examples of string functions."

InStr

<% DIM strPosition strPosition = InStr(1, strExample, "examples", 1) Response.Write strPosition %>

In this example, our script returns the value: 11 . The InStr function is a powerful tool that searches text strings and returns the position of a given text substring. In this case, we search the strPosition string for the "example" and our script returns "11", which is the starting position of the word within the string.

Left

<% DIM strLeftText strLeftText = Left(strExample, 18) Response.Write strLeftText %>

In this example, our script returns the value: " These are examples ". The Left function takes a string and returns a specified number of characters starting from the left side.

Right

<% DIM strRightText strRightText = Right(strExample, 10) Response.Write strRightText %>

In this example, our script returns the value: " functions. ". The Right function takes a string and returns a specified number of characters starting from the end of the string.

Mid

<% DIM strMidText strMidText = Mid(strExample, 11, 8) Response.Write strMidText %>

In this example, our script returns the value: " examples ". The Right function takes a string and returns a specified number of characters starting from the end of the string.

Trim, LTrim, and RTrim

<% DIM strTrimText, strLTrimText, strRTrimText strTrimText = Trim(strExample) strLTrimText = LTrim(strExample) strRTrimText = RTrim(strExample) Response.Write strTrimText Response.Write strLTrimText Response.Write strRTrimText %>

In this example, all three atrTrimText, strLTrimText, and strRTrimText return our original example: "These are examples of string functions." LTrim is used to remove blank spaces at the beginning of a string. RTrim is used to remove blank spaces at the end of a string. Trim is used to remove spaces from both the beginning and the end of a string.

LCase and UCase

<% DIM strLCaseText, strUCaseText strLCaseText = LCase(strExample) strUCaseText = UCase(strExample) Response.Write strLTrimText Response.Write strRTrimText %>

In this example, strLCaseText returns the value: " these are examples of string functions. " and strUCaseText returns the value: " THESE ARE EXAMPLES OF STRING FUNCTIONS. ". As you can tell, the LCase function returns all lower case letters and the UCase function returns all upper case letters. These functions are especially useful for inserting and updating records in your database because they help keep your data consistent.

Len

<% DIM intLenText intLenText = Len(strExample) Response.Write intLenText %>

In this example, intLenExample returns the value: " 39 " . The Len function returns the number of characters in a given string.

String

<% DIM strMyExample strMyExample = String(1, 97) Response.Write strMyExample %>

In this example, strMyExample returns the value: " a " . The String function takes a character code (97) and returns its character (a). The (1) in this case controls how many time the "a" will be displayed.

http://www.aspwebpro.com/aspscripts/functions/string.asp

MATHEMATICAL FUNCTIONS

Math functions allow you to perform a variety of operations on number values in your scripts. Here are some of the most commonly used math functions:

Abs

intResult = Abs(intNumber)

The Abs function takes a number and returns its absolute value.

Exp

intResult = Exp(intNumber)

The Exp function takes a numeric value and returns e (the base of natural logarithms) raised to a power.

Hex

intResult = Hex(intNumber)

The Hex function returns a string value containing the value of an arguement converted to hexadecimal format. If the arguement is a fractional value, it is rounded to the nearest whole number before the function returns the string.

Int

intResult = Int(intNumber)

The Int function returns the whole number portion of a numeric arguement. If the arguement is a negative value, it returns the first integer value that is less than or equal to the arguement.

Fix

intResult = Fix(intNumber)

The Fix function returns the whole number portion of a numeric arguement. If the arguement is a negative value, it returns the first integer value that is greater than or equal to the arguement.

Rnd

intResult = Rnd[(switch)]

The Rnd function returns a random number. Switch indicates how the random number will be determined. If switch is a positive number, the next random number in the sequence should be returned. Before calling this function, you should initialize it by using the Randomize statement.

Sgn

intResult = Sgn(intNumber)

The Sgn function returns a numeric vale representing the sign of a number arguement. It returns 1 if the numeric value is > 0, 0 if = 0, and -1 if < 0.

Sqr

intResult = Sqr(intNumber)

The Sqr function returns the square root of a numeric arguement.

Sin

intResult = Sin(intNumber)

The Sin function returns the sine of an angle.

Tan

intResult = Tan(intNumber)

The Tan function returns the tangent of an angle.

http://www.aspwebpro.com/aspscripts/functions/math.asp

CONVERSION FUNCTIONS

Conversion functions allow you to change the subtype of a variable. VBScript assigns the variant type to all variables as a default, but there are many cases when you might have to convert a variable to a particular type to satisfy an arguement. A common example would be that you might have a string arguement that returns a numeric value or a numeric arguement that returns a string value. Here are some of the most commonly used conversion functions:

CByte

CByte(strExample)

The CByte function converts this variable to a subtype byte.

CDbl

CDbl(strExample)

The CDbl function converts this variable to a subtype double.

CInt

CInt(strExample)

The CInt function converts this variable to a subtype integer.

CLng

CLng(strExample)

The CLng function converts this variable to a subtype long.

CStr

CStr(strExample)

The CStr function converts this variable to a subtype string.

http://www.aspwebpro.com/aspscripts/functions/conversion.asp

SUGGEST USERNAME

If you have a members only website where users can register a unique username and become members, one common inconvenience for your users is that they will try to register a username that has already been registered by someone else. Well, rather than just displaying a message like "That username is already taken, please try a different username." and keep them guessing at usernames, wouldn't it be nice to suggest a similar username to them that is definitely available? Sure it would. Here is how we do it.

The first thing you need to do is create a database called MyDatabase. Then create a table called tblUsers with these fields:
ID - autonumber
fUsername - text field
fPassword - text field
fEmail - text field
fDateEntered - date/time field

Now, enter these usernames into your database: bob, bob1, bob2. The password and email fields are here just as formalities for this exercise.

Next, create a page called register.asp page with the code below

Username:
Password:
Email:


Next, create a page called confirm.asp with the code below:

<% DIM strUsername, strPassword, strEmail strUsername = Request.Form("Username") strPassword = Request.Form("Password") strEmail = Request.Form("Email") IF strUsername <> "" AND strPassword <> "" AND strEmail <> "" THEN

DIM mySQL, objRS
mySQL = "SELECT * FROM tblMembers WHERE fUsername = ' " & strUsername & " ' "
Set objRS = Server.CreateObject("ADODB.Recordset")
objRS.Open mySQL, objConn, adOpenKeyset, adLockPessimistic, adCmdText

IF objRS.EOF THEN
objRS.AddNew
objRS("fUsername")
objRS("fPassword")
objRS("fEmail")
objRS.Update
objRS.Close
Set objRS = Nothing
Response.Write "You have been successfully registered as: " & strUsername

ELSE

DIM X, strTempUsername, intCount, mySQL2, objRS2
DO UNTIL X=True
intCount = intCount + 1
strTempUsername = strUsername & intCount
strUsername = strTempUsername

mySQL2 = "SELECT * FROM tblMembers WHERE fUsername = ' " & strUsername & " ' "
Set objRS2 = Server.CreateObject("ADODB.Recordset")
objRS2.Open mySQL2, objConn, adOpenKeyset, adLockPessimistic, adCmdText

IF objRS2.EOF THEN
X=True
ELSE
intCount = intCount
END IF

LOOP

objRSa2.Close
Set objRSa2 = Nothing

Response.Write "That username has already been registered. Please click Back on your browser and try a different username. "
Response.Write "We suggest you try the below available username:

"
Response.Write "• " & strUsername2 & ""
END IF

ELSE
Response.Write "Please click Back on your browser and complete all three fields"
END IF
%>

That's it! Now, you have a fully automated allbeit simple username suggestion tool. Try testing it. If a user tries to enter "bob", the script will suggest "bob12". If a user tries to enter "bob1", the script will suggest "bob11". Happy registering!

http://www.aspwebpro.com/aspscripts/websitetools/suggestusername.asp

SEARCH ENGINE

So when would you need a search engine on your website. Well, one popular example is an FAQ (frequently asked questions) database. You could merely list all of your FAQ's on one page, but if you have a lot of them like the Micsoft Knowledge Base, then it would be a good idea to let your users search your database by keyword or phrase.

The first thing you need to do is create a database called MyDatabase. Then create a table called tblFAQ with these fields:
ID - autonumber
Question - text field
Answer - text field
DateEntered - date/time field

Then, start adding some questions and answers to your database.

Next, create a page called searchengine.asp and copy the below code into your page:



Search our FAQ's
Enter Search Term



<% DIM strSearchterm strSearchterm = Request.Form("searchterm") IF strSearchterm <> "" THEN
DIM mySQL, objRS
mySQL = "SELECT * FROM tblFAQ WHERE (Question LIKE '%" & strSearchterm & "%') OR (Answer LIKE '%" & strSearchterm & "%')"
Set objRS = Server.CreateObject("ADODB.Recordset")
objRS.Open mySQL, objConn, adOpenKeyset, adLockPessimistic, adCmdText

IF objRS.EOF THEN
Response.Write "Sorry, no records were found for that searchterm"
ELSE
%>

<% DO WHILE NOT objRS.EOF %> <% objRS.MoveNext Loop END IF %>
QuestionAnswer
<%=objRS("Question")%><%=objRS("Answer")%>

<% ELSE ' No searchterm submitted, display blank END IF %>


This script will display your search form each time the page is accessed. When a search term is submitted, it will search both the question and answer fields in your database for any data that contains the search term. There you have it. Your first albeit simple search engine.

http://www.aspwebpro.com/aspscripts/websitetools/searchengine.asp

FORGOT PASSWORD

One common problem with having a secure website is that occassionally members will lose or forget their login password. Well, if you collect their email address when they first register, this is an easy problem to handle. You can simply include a "Forgot Password" where the user enters the email address that they registered with and their password will be sent to them immediately.

The first thing you need to do is create a database called MyDatabase. Then create a table called tblUsers with these fields:
ID - autonumber
fUsername - text field
fPassword - text field
fEmail - text field
fDateEntered - date/time field

Now, create a page called password.asp page with the code below

Email:


Next, create a page called confirm.asp with the code below:

<% DIM strEmail strEmail = Request.Form("Email") IF strEmail <> "" THEN
%>

<% DIM mySQL, objRS mySQL = "SELECT fEmail,fPassword FROM tblMembers WHERE fEmail = '" & strEmail & "'" Set objRS = Server.CreateObject("ADODB.Recordset") objRS.Open mySQL, objConn IF objRS.EOF THEN Response.Write "That email address was not found in our database. Please click Back on your browser and enter the email address you registered with." ELSE DIM strPassword strPassword = objRS("fPassword") DIM mail, objMail Set objMail = Server.CreateObject("CDONTS.NewMail") objMail.From = "email@yourdomain.com" objMail.Subject = "Password" objMail.To = strEmail objMail.Body = "Here is your login password: " & strEmail objMail.Send Set objMail = nothing Response.Write "Your password has been sent to your email address." END IF ELSE Response.Write "Please click Back on your browser and enter the email address you registered with." END IF %>

In this example, we are using the CDONTS email component to send our email. You can easily replace this with a different email component script like ASPMail or ASPEmail. That's all there is to it. Now, you have a fully automated Forgot Password tool that your website members can use anytime without hassle. That's customer service!

EMAIL THIS PAGE

Another simple and very valuable tool to add to your website is the Email This Page tool. In this example, you can allow users to send the URL of any page within your website to any email address they choose. For our purposes, we will use ASPMail for sending mail

First, place this link on your home page:


ASP Web Pro




Email This Page




Next, create a page in your root directory called emailthispage.asp and paste the following code:


ASP Web Pro




<% DIM strURL strURL = Request.ServerVariables("HTTP_Referer") IF strURL = "" THEN Response.Write "Sorry, your browser does not support this function." END IF %>

Page Link: <%= strURL %>


Your Email:
Your First Name:
Recipient's Email:
Recipient's First Name:
Comments:







Last, create a confirmation page called emailthispageconfirm.asp, paste the following code, and customize it with your own domain name and mailing info:


ASP Web Pro




<% DIM Mailer, strEmail, strMsgHeader, qryItem, strMsgInfo DIM strYourEmail, strYourName, strRecipEmail, strRecipName, strComments, strURL, Mail strYourEmail = Request.Form("YourEmail") strYourName = Request.Form("YourName") strRecipEmail = Request.Form("RecipEmail") strRecipName = Request.Form("RecipName") strComments = Request.Form("Comments") strURL = Request.Form("URL") Set Mailer = Server.CreateObject("SMTPsvg.Mailer") Mailer.FromAddress = strYourEmail Mailer.ReplyTo = strYourEmail Mailer.RemoteHost = "YOUR_DOMAIN_NAME.COM" Mailer.AddRecipient strRecipName, strRecipEmail Mailer.Subject = "Look at this page from the YOUR_WEBSITE_NAME_HERE website" strMsgHeader = "This mail message was sent from the YOUR_DOMAIN_NAME_HERE website" & vbCrLf & vbCrLf Mailer.BodyText = strMsgHeader & vbCrLf & strRecipName & "," & vbCrLf & vbCrLf & strYourName & " wants you to take a look at this page at YOUR_WEBSITE_NAME_HERE:" & vbCrLf & "Page Link: " & strURL & vbCrLf & vbCrLf & strComments IF Mailer.SendMail THEN %>
<% strYourName = request.form("YourName") Response.Write strYourName %>
,

Thank you for sharing this page with
<% strRecipName = request.form("RecipName") Response.Write strRecipName %>
. Your message has been sent successfully and will be received by
<% strRecipName = request.form("RecipName") Response.Write strRecipName %>
shortly.

<% ELSE Response.Write "Sorry, there was an error and your email could not be sent at this time." END IF %>




That's all there is to it. The confirmation page is even customized so that it displays the sender's and recipient's names. Now, anytime one of your website users sees something interesting, they can email that page link to any email address they want. In essence, it helps drive more traffic to your website!

http://www.aspwebpro.com/aspscripts/websitetools/emailthispage.asp

Tuesday, 29 November 2011

DISPLAY RANDOM TEXT

Ever wanted to display random tips or quotes on your website? Well, Look no further. Here is a random text displayer that we used on a website we built that displays a random tip every time the browser is refreshed.

The first thing you need to do is create a database with a table called tblQuickTips with these fields:
fID - autonumber
fTip - text field or memo field depending on how long your tips are

Then, start adding some tips to your database.

Next, create a page called randomtext.asp and copy the below code into your page:

<% DIM mySQL, objRS mySQL = "SELECT MAX(fID) AS MaxTip FROM tblContent_Quick_Tips" Set objRS = Server.CreateObject("ADODB.Recordset") objRS.Open mySQL, objConn Randomize DIM intRecord intRecord = Int(objRS("MaxTip") * Rnd + 1) objRS.Close Set objRS = Nothing mySQL2 = "SELECT fTip FROM tblContent_Quick_Tips WHERE fID = '" & intRecord & "'" Set objRS2 = Server.CreateObject("ADODB.Recordset") objRS2.Open mySQL2, objConn Response.Write objRS2("fText") objRS2.Close Set objRS2 = Nothing %>

All done. Just publish your page and database and click refresh on your browser. Each time you refresh, a random tip will be displayed.

http://www.aspwebpro.com/aspscripts/contentmgmt/randomtext.asp

DISPLAY CONTENT FROM ANOTHER WEB SITE

Occasionally, it is necessary to retrieve content from another web site and display it in your own web pages. Of course, now a days most web sites that allow you to use their content on your web pages will already have their own system in place where you will just add some basic HTML to your pages and their content will display automatically so you wouldn't need this.

For those few instances, though, where you might need to do this, here is how. Assuming that you have permission to use their content, place the below script into your source code and add the URL of the page you want to retrieve the content from.

<% Set objHTTP = Server.CreateObject("Microsoft.XMLHTTP") objHTTP.Open "GET", "http://www.domainname.com", false objHTTP.Send Response.Write objHTTP.ResponseText %>

Granted, this is a limited script so it may not suit all of your needs, but chances are if you want to do something more sophisticated than this, you probably should not be using this script. I realize this is a very touchy subject today so please use this script wisely and ALWAYS GET PERMISSION FIRST!

http://www.aspwebpro.com/aspscripts/contentmgmt/displayfromothersite.asp

BANNER AD ROTATOR

If you want to rotate banner advertisements on your web page, you are in luck. You can use the simple and straight forward Ad Rotator component, which comes standard with ASP.

The first thing you need to do is create a text file called adrotator.txt and copy the code below:

REDIRECT /anyfile.asp
WIDTH 468
HEIGHT 60
BORDER 1
*
http://www.YOUR_DOMAIN_NAME.com/images/banner1.gif
http://www.ADVERTISER1_DOMAIN_NAME.com
Visit Advertiser1 now!
25
http://www.YOUR_DOMAIN_NAME.com/images/banner2.gif
http://www.ADVERTISER2_DOMAIN_NAME.com
Visit Advertiser2 now!
25
http://www.YOUR_DOMAIN_NAME.com/images/banner3.gif
http://www.ADVERTISER3_DOMAIN_NAME.com
Visit Advertiser3 now!
40
http://www.YOUR_DOMAIN_NAME.com/images/banner4.gif
http://www.ADVERTISER4_DOMAIN_NAME.com
Visit Advertiser4 now!
10

This schedule has four banner ads in it. The top four lines are optional, but the * is required. The Redirect send all banner ad clicks to a specified ASP file, you can use this option if you want to track banner ad statistics. The Width and Height set the dimensions of the banner ad, and the Border sets the border thickness around the banner.

After the *, you can list as manny banners as you want. Each banner that you list, consists of four lines: 1) URL of banner ad image; 2) URL users will be sent to when they click on the banner ad; 3) the image ALT text; and 4) the percentage of time that you want the banner to display on the page (must total 100 naturally).

Next, paste the following code to any ASP page where you want to display your banner ads:

<% DIM strBanners Set strBanners = Server.CreateObject("MSWC.AdRotator") Response.Write (strBanners.GetAdvertisement("/adrotator.txt")) %>

All done. Now you have a professional looking banner ad rotation system. Now, it's up to you to go out and find some advertisers!

http://www.aspwebpro.com/aspscripts/contentmgmt/banneradrotator.asp

READ ASP COOKIES BASICS

OK, you have a script that writes an asp cookie and now you need to read the cookie each time the user returns to your website. It's really quite simple. First, we declare a few variables and then we use Request.Cookies to read the cookie from the browser and get our values.

For this example, let's say that you have a secure website that uses a username and password combination. When a user becomes a member of your site, you simply write an asp cookie to their browser that stores their username and password and any other data you want. By doing this, you can read the username and password data from the cookie each time the user returns to your site and use another ASP script to validate the cookie data with your database data. As long as the cookie data matches your database data, the user will be able to use your secure web site without any interuption.

Here is how the script looks:

<% DIM strUsername, strPassword, strFirstName, strLastName strUsername = Request.Cookies("MyCOOKIE")("Username") strPassword = Request.Cookies("MyCOOKIE")("Password") strFirstName = Request.Cookies("MyCOOKIE")("strFirstName") strLastName = Request.Cookies("MyCOOKIE")("strLastName") %>

Just replace MyCOOKIE with your own cookie name and you are on your way.
Be sure to choose a unique cookie name to use for your site. If you use a basic name like "MyCOOKIE" like in the example above, the user may visit another website that uses the same cookie name and it could write over your cookie data!

WRITE ASP COOKIES BASICS

A great way of personalizing your website is through the use of asp cookies. There are a lot of things that you can do with asp cookies. This script shows you how to write basic asp cookies to the browser:

<% Response.Cookies("MyCookie")("Domain") = "www.YourDomainHere.com" Response.Cookies("MyCookie")("Expires") = Date() + 1 Response.Cookies("MyCookie")("Name") = "WebUser" %>

There you have it, now you can write asp cookies. What happens next though? After you write the cookie, you need to read it when the user returns, right? Check out Read ASP Cookies Basics to learn how.
http://www.aspwebpro.com/aspscripts/miscellaneous/writecookiebasics.asp

REDIRECT USER

There are a lot of cases in ASP where you would need to redirect or send a user from one page to another. One example would be if you have a membership based website. When the user logs in with his/her username and password, this information is checked by a verification script. If their login is verified, they are sent to the member page. If there username and password is incorrect, they are sent to an error page. Redirecting users is easy and only consists of one line of code:

<% Response.Redirect("/index.asp") %>

All you have to do is enter the relative path to the desired page and away your user goes!

http://www.aspwebpro.com/aspscripts/miscellaneous/redirectuser.asp

PRINTER FRIENDLY PAGE

A lot of websites include valuable information that needs to be printed by the user. It could information like a news article, instructions, directions, or anything else. Sometimes you may even want your entire website to be printable. The problem is that when you print your page, the printout is not formatted correctly and all of these extra banners, menus, etc get printed as well. Well this "Printer Friendly Page" is the answer you have been looking for. There are actually a few different ways to accomplish this, here is one of them.

All you have to do is create a page called printerpage.asp and copy the code below:


Printer Friendly Page

<% DIM view view=request.querystring("view") IF view <> "print" THEN
%>

My Website Menu

History

Products

Services
Print this information.

 

?view=print">Printer Friendly Page

<% ELSE %>

Print this information.


?view=view">Return to Regular View

<% END IF %>




The first time you access the page, it will display your banner and menu items. If you click the Printer Friendly Page link, the page will refresh itself with only the text you want printed.

http://www.aspwebpro.com/aspscripts/miscellaneous/printerfriendlypage.asp

SERVER VARIABLES

One way of collecting valuable web statistics is through the use of server variables. Server variables retrieve information from the user's browser. You can use these to get all kinds of useful information, such as browser details, connection methods, and more. To get a list of all of the available server variables, create a servervariables.asp page with the code below:

<% FOR EACH SV IN Request.ServerVariables Response.Write "

" & SV & " = " & request.servervariables(SV) & "

"
NEXT
%>

Next, simply publish the page and open it on the Internet. It will display a list of them for you.

http://www.aspwebpro.com/aspscripts/statistics/servervariables.asp

DOWNLOAD TRACKER

Another popular web statistic that is valuable to track is how many times an item has been downloaded. This may seem a little more indepth than our other web statistic scripts, but just take it step by step and you will make it. This little script will track the title of each item that is downloaded and it will track how many times it was downloaded each day.

The first thing you need is a file to be downloaded. For our purposes, we will say that we want to download this file: http://www.aspwebpro.com/downloads/document.txt.

Second, create a web page called downloads.asp within you root directory. Then, add a hyperlink on your web page like this:

< a href="includes/downloadtracker.asp?Title=MyDocument&File=document.txt">Download My Document Here

Third, create a new table called tblDownloads in your Access database and give it these fields:
ID - Autonumber
fTitle - Text, 255
fFile - Text, 255
fDownloads - Number
fDateDownloaded - Date/Time

The fourth step is creating the downloadtracker.asp page. First, create an /includes folder within your root directory. Next, create a blank page and copy the below code into it. Lastly, save the page as downloadtracker.asp and save it within your new /includes directory.



<% DIM mySQL, strTitle, strFile, strDate, objRS strTitle = Request("Title") strFile = Request("File") strDate = Date() mySQL = "SELECT * FROM tblDownloads WHERE fTitle = ' " & strTitle & " ' AND fDateDownloaded = ' " & strDate & " ' ;" Set objRS = Server.CreateObject("ADODB.Recordset") objRS.Open mySQL, objConn, adOpenKeyset, adLockPessimistic, adCmdText IF objRS.EOF THEN objRS.AddNew objRS("fTitle") = Request("Title") objRS("fFile") = Request("File") objRS("fDownloads") = 1 objRS("fDateDownloaded") = Date() objRS.Update ELSE objRS.MoveFirst DIM intCount intCount = objRS("fDownloads") objRS("fDownloads") = intCount + 1 objRS.Update END IF objRS.Close Set objRS = Nothing objConn.Close Set objConn = Nothing Response.Redirect("/downloads/" & Request("File")) %>

All "mySQL" statements should appear on one line in your source code to function properly.

Just create a /downloads folder within your root directory and place all of your downloads within it. Believe it or not, that's it! Now you can track which items are being downloaded from your website, how often, and how many downloads occur.

http://www.aspwebpro.com/aspscripts/statistics/downloadtracker.asp

TOTAL HITS WITH TEXT FILE

On way to track the number of hits that your website receives is by using a text file counter.

The first thing to do is create a text file called totalhits.txt and save it within a directory called statistics.

Then, all you have to do is include the code below at the top of every page that you want hits counted from:

<% Set FileObject = Server.CreateObject("Scripting.FileSystemObject") HitsFile = Server.MapPath ("/statistics") & "\totalhits.txt" Set InStream= FileObject.OpenTextFile (HitsFile, 1, false ) OldHits = Trim(InStream.ReadLine) NewHits = OldHits + 1 Set OutStream= FileObject.CreateTextFile (HitsFile, True) OutStream.WriteLine(NewHits) %>

That's it. Now, you've got yourself a hit counter that uses a good old fashioned text file

http://www.aspwebpro.com/aspscripts/statistics/totalhitstxt.asp