Online Shopping Cart - Part 1
Programming concepts for developing an online shopping cart system
E-commerce oriented domains have a wide range of needs; the solutions implemented to fulfill such needs are also wide ranging in terms of the resources, architecture, and technology used. Large e-commerce oriented domains have dedicated servers that handle just e-commerce related functions and carry out the complicated 'business logic' involved in working out totals, discounts, shipping charges and logistics while Smaller sites with simpler needs make do with a few simple routines that allow users to select a range of products and place orders. An online shopping cart is quite similar to a real one; only, it is virtual. In the real world, users throw a number of items into the shopping cart and finally proceed to the check out counter to buy the products.
In the virtual world, users click on a representation or the name of the item they want. A Session variables or some other mechanism is used to keep track of the code, cost, and quantity of the item picked. A 'click' selection of this sort constitutes an addition to the customer's cart. A list of the items picked and each item's details are maintained - this is the 'shopping cart'. A customer is allowed to 'view' his or her cart - a program retrieves the list of items, calculates the total cost and displays the list to the user. The user is also allowed to remove items from the cart - the program simply removes items from the list it maintains. The customer may place an order - clicking on the order button redirects him or her to a page where she may select a shipping method and make an online payment.
Our shopping cart application will not deal with online payments. We will simply maintain a shopping cart; the items in it will be saved in the database if the customer should click on the place order button.
We will store the items in our list in a VBScript Dictionary object. To read more about this object, look it up in the VB Script Programming Reference. The dictionary object is actually an array. However, each item in the array (which can itself be an array or any type of Object) is associated with a unique descriptive key rather than a numerical index. The key is usually an integer or a string. Our dictionary object will have the item name as a key. Its value will be an array with two elements - the first element will be cost of the item and the second element will contain the number of times the user picked the item (quantity).
The user may add some items to his shopping cart, browse the site or visit other sites, and then come back later and add an item or place an order. How do we keep track of the items on the cart? We will preserve the entire Dictionary object with the list of picked items, their cost and quantity in a session variable. Whenever required, we will put the contents of this session variable into a normal variable, change the normal variable, and once more assign the session variable to the updated regular variable.
First, let us change catalogue.asp so the user may add items to the cart. We do this by adding a new column with an 'add to cart' link in the table that contains the catalogue items. This new column should have the following header: '<TH >Click to Order</TH>'. Add this header next to the "Price" header in catalogue asp. The link that will go under this column will hold information about that row's item (name
The florist web site now has a registration application in place. This is practically useless unless a sign in and sign out application that incorporates the login ID and password chosen by the user is implemented. We will set about doing just this in this exercise.
First, create the Florist Web Site Login Page "login.htm" and save it in Inetpub\wwwroot\florist. Copy register.asp's skeleton (all the way to the <hr> element) into the empty login.htm file and change the text within the <h1> tags to Please Sign In\Out. Make the following modifications.
The page should contain an extra navigation link on the top right under the 'Register' link with the caption "SignIn\Out". This link should point to this very file, login.htm. Simply copy the registration navigation div and place the copy right under it. Rename the new div to 'logindiv', change the caption to 'SignIn\ Out' (exactly this so the div size remains uniform) and add 23 pixels to the 'top' element in the inline style definition. Add an extra <br> tag after the heading to accommodate the new navigation button.
Change the links on the login.htm file to point to asp files rather than the old html files. That is, 'Catalogue' should point to 'catalogue.asp' and 'Register' should point to 'register.asp'. The other two links point to plain HTML files.
Note: This is a good time to extend the above two changes in the skeleton to all the other 'display' pages - catalogue.htm, register.asp, and florist.html. Display pages are actually viewed by the user at point, as opposed to pages like saveuser.asp that contain only ASP code and redirection directives. Rename catalogue.htm to catalogue.asp. Don't forget to change the inline links in the text paragraphs in florist.html, the home page. The changes that follow pertain only to login.htm
Remove all the ASP code from the skeleton. You can search for all the content between <% and %> and remove such sections
Remove the setCookie(), preloadform(), and dostuff() Javascript functions from login.htm.
Delete all the sections from the validate() function that follow the validation of the password field. In other words, delete all the code starting from and including the line 'if(document.forms.register.password1.value != document.forms.register.password2.value)' until and including the line 'setCookie(favFlower);'
Replace 'document.forms.register' where ever it occurs with 'document.forms.loginform'. The rest of the string may remain the same.
The body tag should read <body onLoad=displayFav()> and not contain a reference to the doStuff() function.
Add the following HTML markup after the <hr> tag. Only the closing BODY and HTML tags should follow the following markup.
<br><br> <form name=loginform onSubmit="return validate()" action="checklogin.asp" method="post"> <table align=center> <tr> <td>Login: </td><td><input type=text name=login /></td></tr> <tr><td>Password: </td><td><input type=password name=password1 /></td></tr> <tr><td colspan=2 align=center><input type=submit name=go value="GO!" /></td></tr> <tr><td>New User? </td><td><a href=register.asp>Register With Us!</a></td></tr> <tr><td> </td><td> </td></tr> <tr><td colspan=2 style="text-align:center"> <a href=checklogin.asp?action=logout>Sign Out</a> </td></tr> </table> </form>
The above markup represents a form named loginform and its content. This form has a login field and a password field. A Javascript function validate() is used to check user input upon form submission. This function is identical (except for the name of the form object) to the one in register.asp. Only, it contains just two sections that validate its two fields. The action attribute of the form points to 'checklogin.asp'.
The form also contains two links. the 'Register' link points to the registration ASP page and the 'Sign Out' or log out link also points to checklogin.asp (the script mentioned in the action attribute of the form tag). However, the 'Sign Out' link takes a querystring with the parameter action set to logout. Logging in a user in our context simply means setting a session variable to reflect the login ID if the user has entered a valid login ID and password in the login form. Additionally, we can set the cookie to reflect the user's favorite flower. Logout is simply the reversal the login actions: both the "login" session variable and the cookie should be reset. Obviously, users who enter invalid login and password should be intimated of their error and made to enter fresh values. Checklogin.asp's command flow is as follows
If the request is for logout
Reset the "login" session variable
Reset the cookie that contains user's favorite flower
Display a goodbye message
Redirect to the home page
If the request is for login
Open the database
If the login and password entered by the user match entries
in a row in the 'users' table
Set the "login" session variable to the login ID of the user
Set the cookie to the first of the user's favorite flowers
Display a welcome message
Redirect to the Home Page
Else if no match is found in the 'users' table
Display an invalid login message
Direct to the login page once more to get a valid entry
, quantity, and cost) in its querystring.
Additional code is highlighted.
<TR><TD> <table> <tr><td align=center> <a href=# onClick="showLarge(<%= flowernum%>)"> <img src="images/<%= itemimage%>" name="<%= itemshort %>" alt="<%= itemname %>" width=200 height=140></a></td></tr> <tr><td align=center> <a href=# onClick="showLarge(<%= flowernum%>)"><%= itemname %></a></td></tr> </table> </TD> <TD><%= itemdescription %></TD> <TD><%= itemcost%></TD> <td style="text-align:center"> <a href= "addtocart.asp?flower=<%= itemshort%>&quantity=1&cost=<%= itemcost%>"> Add to Cart</a></td> </TR>
The new line opens a link called addtocart.asp. This link sends the flower's short hand, cost, and the quantity to addtocart.asp through the query string. We have designed this application in such a way that the user will have to click on the appropriate 'Add to Cart' link twice if she wants to place an order for two bouquets, three times if she wants to place an order for three bouquets and so on. Also, ASP response.write short hand is used to add the values to the query string because each item is dynamically loaded from the database. Next, let us add a button that will allow the user to view all his selections. Add the following line right before the </TABLE> closing tag. The HTML markup is for a stand alone submit button that opens a window when clicked. The source file for the window is the viewcart.asp script.
<input type=submit onClick=window.open("viewcart.asp","cart","height=240,scrollbars,resizable") name=view value="View Cart" /></a></td></tr> Next, open a new file called addtocart.asp. This script basically keeps track of the user's shopping cart by adding items to the Dictionary Object we will use.
<% if session("login") = "" then response.Redirect("login.htm") end if Dim shoppingCart Dim itemName, itemArray If IsObject(Session("shoppingCart")) Then Set shoppingCart = Session("shoppingCart") Else Set shoppingCart = Server.CreateObject("Scripting.Dictionary") End If %>First, the user is sent to the login page if he or she is trying to add items to the shopping cart without being logged in.
Next, we check to see if the shopping cart session object already exists using the IsObject command.
If it exists, we dump its contents into an ordinary dictionary object for our use; session variables should not be manipulated directly. At the end of the script, we will dump the contents of theplain shoppingCart variable with all the changes we made back into the session variable.
If the user is adding an item to the cart for the first time, we create a new Dictionary object called ShoppingCart.
<% itemName = request.querystring("flower") itemArray = _ Array(cint(request.querystring("quantity")), _ ccur(request.querystring("cost"))) If shoppingCart.Exists(itemName) Then currentValArray = shoppingCart(itemName) currentValArray(0) = currentValArray(0) + itemArray(0) currentValArray(1) = currentValArray(0) * itemArray(1) shoppingCart(itemName) = currentValArray Else shoppingCart.Add itemName, itemArray End If Set Session("shoppingCart") = shoppingCart response.Redirect("catalogue.asp?add=done") %>Next, we retrieve values from the querystring. The flower name is put into the itemName variable; this variable will serve as the key for our Dictionary Object.
The quantity and cost are converted to an integer and currency value using the cint and ccur functions respectively. They are made into the first and second element in an Array called itemArray
the Exists function of the dictionary object returns true if a key that atches the parameter passed into it (itemName) is found. If the key is found, we know that the user is trying to add one more item of the same type to the cart.
We dump the contents of the value for that key (shoppingCart(itemName) refers to this value) into a temporary variable called currentValArray. Note that currValArray contains two items - the number of products of 'itemType' ordered and the total cost.
We add the quantity passed in (always one in our case) to the quantity already stored and calculate the new total cost by multiplying the new quantity by the cost that was passed in through the querystring. Since these changes are made to currValArray, "shoppingCart(itemName) = currentValArray" puts our changes back into the value of the Dictionary Object pointed to by 'itemname'
If a key matching 'itemname' is not found, we know that we have to add a new key-value pair to the dictionary object. Since infoArray already contains the cost and quantity, we simply use the add method of the dictionary object to add a new key value pair with 'itemname' for the key(shoppingCart.Add itemName, itemArray)
Finally, we update the session variable with the changes we made to the shopping cart and lead the user back to catalogue.asp with the querystring 'add' parameter set to 'done'. The following Javascript should be added to catalogue.asp right after the 'script' tag. This code displays a successful addition message to the user and resets the querystring.
var queryString = window.location.search.substring(1); if (queryString.length > 0) { alert("Item Added to Cart!"); window.location.search = ""; }Once you have completed the above changes, add a few items to the cart and see if you get the success message every time. Next, create a file called viewcart.asp with the following initial code
<% if session("login") = "" then response.Redirect("login.htm") end if %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Shopping Cart</title> <link rel="stylesheet" type="text/css" href="style.css"/> </head> <body bgcolor=#F1BBD6> <% Dim Key,shoppingCart Dim runningTotal, infoArray If IsObject(Session("shoppingCart")) Then Set shoppingCart = Session("shoppingCart") Else Set shoppingCart = Server.CreateObject("Scripting.Dictionary") End If %>Learn Free!
- Microsoft Word
- Microsoft Excel 2003
- Microsoft Powerpoint
- Microsoft Access
- Microsoft Outlook
- Microsoft Visio 2003
- Computer Hardware
- Building Your PC
- Programming
- VB.NET Basics
- C# Basics
- Web Development
- 01 - Introduction
- 02 - Web Development Basics
- 03 - Basic HTML Tags and Style Sheets
- 04 - Frames, Forms, and More
- 05 - Client Side Scripting Concepts
- 06 - Dynamic HTML and Cookies Using Javascript
- 07 - Setting Up The Server Environment
- 08 - Web Application Development Using ASP
- 09 - Online Shopping and Security
- 10 - Design, Architecture and Current Trends
- ASP.NET Basics
- Java Basics
- XML Basics
- Perl Basics
- Linux Basics
- Photoshop Basics
- Database Basics
- Microsoft SQL Server
- Oracle Basics
- eBay Basics
- Opening an Online Store
- Success Basics
- Debt Management