Home » Web Development » 09 - Online Shopping and Security
9

Online Shopping Cart - Part 2

Programming concepts for developing an online shopping cart system

Other than the HTML markup, the above code is more or less identical to the code at the start of the addtocart file. We do not want users who are not logged in to view the cart. In case the user has clicked this button without ever adding anything to the cart, we create a new dictionary object so that an error is not displayed on the browser when we try to access the object. Otherwise, we copy the session variable into a non-session Dictionary object for our use. A few variables - Key, ShoppingCart, runningTotal, and infoArray - are declared. The following section is simple enough; it is just the HTML markup for the cart table's column header.

<TABLE width=100%>
            <TR>
                        <Th style="text-align:center">Item</Th>
                        <Th style="text-align:center">Quantity</Th>
                        <Th>Remove From Cart</Th>
                        <Th style="text-align:right" >Price</Th>
            </TR>
        <%

The following code is executed as many times as there are keys in the Dictionary object, i.e, once for each catalogue item the user has added. The running total is initially set to zero and incremented each time through the loop to get a grand total. Each loop prints a row that contains (a) an item on the shopping cart, (b) its quantity, and (c) cost for the quantity purchased.

    
runningTotal = 0
        For Each Key in shoppingCart
 
            infoArray = shoppingCart(Key)
                runningTotal = ccur(runningTotal) + infoArray(1)
                %>
                <TR>
                        <TD ALIGN="Center"><%= Key %></TD>
 
                        <TD ALIGN="Center"><%= infoArray(0) %></TD>
                        <TD ALIGN="Left">
                        <A HREF=
                        "delfromcart.asp?flower=<%= Key %>&quantity=1">
                        Remove One</A>
                          
                        <A HREF="delfromcart.asp?flower=<%= Key %>&quantity=<%= infoArray(0) %>"
                        >Remove All</A></TD>
                        <TD ALIGN="Right">$<%= infoArray(1) %></TD>
                </TR>
                <%
        Next
        %>

Also, 'remove from cart' links are printed on each row. These links take the user to the delfromcart.asp script. The query string for this link is set to contain appropriate values. Note that the user is offered two choices - he may either decrement the selected quantity of the item by 1 or completely the item. The remove one link has '1' hard coded into the querystring value; the remove all link's querystring value is populated by the total quantity from the dictionary object.

    
<TR><TD COLSPAN=4 ALIGN="Right"><B>
        Total: $<%= runningTotal%></TD></TR>
        <TR><TD COLSPAN=4 ALIGN="Center">
        <input type=submit name=order
        onclick="document.location.href='placeorder.asp'"
        value="Place Order!"/></TD></TR>
        </TABLE>

</body>
</html>

Finally, we display the grand total after exiting the for loop and also display a button that allows the user to place an order for the items in the cart. Note that we did not assign the shoppingCart non-session object back to the session object; there is no need to - no changes were made to the object; the cart was just read and displayed. After you have saved the viewcart.asp file, click on the 'View Cart' button and see if everything works the way it should. Now, let us work on the delfromcart.asp script.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%
Dim shoppingCart,infoArray
Dim itemName
Dim itemQuantity

itemName = request.querystring("flower")
itemQuantity = request.querystring("quantity")

If IsObject(Session("shoppingCart")) Then
        Set shoppingCart = Session("shoppingCart")
Else
        Set shoppingCart = Server.CreateObject("Scripting.Dictionary")
End If

The above code is identical to code in the other scripts. It redirects users who are not logged in to the login page. In case the user has clicked this button without ever adding anything to the cart, we create a new dictionary object so that an error is not displayed on the browser when we try to access the object. Otherwise, we copy the session variable into a non-session Dictionary object for our use.


If shoppingCart.Exists(itemName) Then
        currValArray = shoppingCart(itemName)
                If (currValArray(0)) <= cint(itemQuantity) Then
                        shoppingCart.Remove itemName
                Else
                    itemCost = currValArray(1)/currValArray(0)
                        currValArray(0) = currValArray(0) - cint(itemQuantity)
                        currValArray(1) = currValArray(0)* ccur(itemCost)
                        shoppingCart(itemName) = currValArray
                End If
 
End If

Set Session("shoppingCart") = shoppingCart

response.Redirect("viewcart.asp")
 
%>

The above code does the opposite of what the addtocart script achieved. If the item exists in the cart, it checks if the quantity of the item in the cart is less than or equal to the value passed in through the querystring. If so, the user has indicated that he wants all items of the type pointed to by itemName removed. We use the remove method of the Dictionary Object to remove the key-value pair from the Object. If not, we perform mathematical calculations to subtract one from the quantity and arrive at a new cost. Since we only have the total cost for the quantity, we first divide the total cost by the initial quantity to get the cost per item and then multiply this cost by the new quantity (after subtracting one). Finally, we update the session object and lead the user back to the cart view window.

The placeorder file is the final file in this group; it simply gets the current date using the VB Now function, goes through the Dictionary Object, extracts the item name, quantity, and cost, and inserts a new row in the order table for each item. After the items have been added to the table, a success message is displayed and the shoppingCart session variable is reset; we do not want a duplicate order. Finally, the cart view window is closed. The conditional statement 'if IsObject...' and 'if shoppingCart.count .. ' check if the Shopping cart either does not exist or is empty; in both cases, the user is shown a message that says that he or she cannot place an empty order.

<%
if session("login") = "" then
        response.Redirect("login.htm")
else
        login = session("login")
end if

Dim shoppingCart, Key
Dim itemName
Dim itemQuantity

If IsObject(Session("shoppingCart")) Then
        Set shoppingCart = Session("shoppingCart")
today = Date

set conn=Server.CreateObject("ADODB.Connection")
conn.Mode = 3
conn.open "florist","",""

        if (shoppingCart.count > 0 ) then
           For Each Key in shoppingCart
 
                 infoArray = shoppingCart(Key)
 
                 conn.Execute "insert into orders (login,orderdate,item,quantity,cost)" _
                 & "values" _
                 & "('" & login & "'," & today & ",'" & key & "'," _
                 & infoArray(0) & "," & infoArray(1) & ")"
           next
           conn.Close
           set conn = nothing

           alertMsg = "Order Placed Successfully!"
    else
            alertMsg = "Please Order Something First!"
    end if
else
    alertMsg = "Please Order Something First!"
end if

Session("shoppingCart") = ""

 %>

<html><head><script language=javascript>
alert("<% =alertMsg%>")
window.close()
</script></head></html>

Finally, a small change should be made to checklogin.asp in the Sign Out section. We will empty the shopping cart when the user signs out of the domain. The highlighted code should be added in the appropriate place in checklogin.asp

<%
if (request.QueryString("action") = "logout") then
    Session("login") = ""
    If IsObject(Session("shoppingCart")) Then
              session("shoppingCart") = ""
    end if    %>

Once you have incorporated all these changes, you are ready to test the shopping cart application. If errors persist, use the Zip File with all the code to check your scripts. Our simple online order application works on the same lines as over half of all of such applications on a wide spectrum of web sites. You may try to enhance this application by merging the add, delete, view, and order scripts into a single script with a control flow that executes parts of the script based on query string variables. This is a good design decision because a lot of code appears over and over again in four scripts that form the shopping cart application.

Screenshot 9a: Cart View Window

Screenshot 9a: Cart View Window