Приглашаем посетить
Грин (grin.lit-info.ru)

7.5 Implementation of an online shopping cart

Table of Contents

Previous Next

7.5 Implementation of an online shopping cart

One of the popular applications of cookies is to develop the so-called "Online Shopping Cart." When a customer visits a cyber store (i.e., online shopping), it is likely that he or she will go through pages and pages of products in different categories. Often, the customer may pick up some bargains but then change his or her mind later. An efficient way to store shopping items with the flexibility to add or delete through pages is to use cookies. Another main advantage is that cookie information is usually stored on a local machine containing user information. From a business point of view, cookies are excellent tools for tracing special or potential customers and targeting them for business purposes.

The main aim of this example is to show you a cut-down version of a shopping cart. More importantly, this case study demonstrates how to format a Web problem, solution techniques, and how to put client-side scripting language into practical action at the same time. The last is necessary for further study of Web technologies.

Now, let's see how XHTML features can be integrated with Web programming and used as an excellent tool for program interfacing.

7.5.1 Using XHTML as an interface

From a Web programmers' point of view, markup languages or elements in general can be considered as a programming interface. In fact, they are the interface between the Internet (or World Wide Web) and the users. In particular, when working with other Web technologies, languages such as XHTML provides a universal and excellent tool for human and machine interrogation. The first interface and control that we would like to introduce here is called the "checkbox."

A checkbox is a small box on a Web page and can be generated by the following XHTML statement:



<input style="height:25px;width:25px"
    type="checkbox" id="CheckBox1" name="CheckBox1" />

This is a 25 x 25 pixels box with identity "CheckBox1." When you perform a mouse click inside the box, a "tick" symbol will appear inside it. That is, you can use a mouse click to check and uncheck the box. Since there is no user input (or typing) involved, errors can be minimized.

With scripting techniques, you can check and uncheck this box by assigning a value to the variable document.getElementById("CheckBox1").checked such as:



document.getElementById("CheckBox1").checked=1 - checked
document.getElementById("CheckBox1").checked=0 - unchecked

This variable can also be used to test whether a box has been checked.

Our project in this section is to write a Web page to sell some computer equipment online. The items and prices are listed as follows:



Color Laser Printer    400
CD-RW (20x20x60)       100
Digital Camera         100
Monitor (19 inch)      170

Using checked boxes, the interface implementation of this page has a simple form (ex07-19.htm):



Example: ex07-19.htm - Online Shopping Cart I

 1: <?xml version="1.0" encoding="iso-88591"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title>Online Shopping Cart I -- ex0719.htm</title></head>
 6: <style>
 7:   .tx01{background-color:#000088;font-family:arial;
 8:      font-size:14pt;color:#ffff00;text-align:left}
 9:   .tx02{font-size:22pt;color:#00ffff}
10:   .butStyle{background-color:#aaffaa;font-family:arial;
11:      font-size:14pt;color:#008800;width:170px;height:35px}
12: </style>
13:
14: <body class="tx01" style="text-align:center">
15: <span class="tx02">Today's Special Buy</span><br />
16: <img src="line1.gif" width="450" height="6" /><br /><br />
17:
18: <script src="cookie.js"></script>
19: <script src="online.js"></script>
20: <script>
21:   initialAll()
22:   userName = getCookie("UserName")
23:   outMsg="For: "+userName+" (Half Price!)"
24:   document.write(outMsg)
25: </script><br /><br />
26:
27: <table border="0" align="center"><tr align="center">
28:     <td width="200">Description</td><td width="120">Price (USD)</td>
29:     <td width="150">Put In <br /> Shopping Cart</td></tr>
30:   <tr align="center"><td>Color Laser Printer</td><td>400</td>
31:     <td><input style="height:25px;width:25px"
32:           type="checkbox" id="prt" name="prt" /></td></tr>
33:   <tr align="center"><td>CD-RW (20x20x60)</td><td>100</td>
34:     <td><input style="height:25px;width:25px"
35:           type="checkbox" id="cdrw" /></td></tr>
36:   <tr align="center"><td>Digital Camera</td><td>100</td>
37:     <td><input style="height:25px;width:25px"
38:           type="checkbox" id="cam" /></td></tr>
39:   <tr align="center"><td>Monitor (19 inch)</td><td>170</td>
40:     <td><input style="height:25px;width:25px"
41:           type="checkbox" id="mon" /></td></tr>
42: </table><br />
43: <input type="button" value="Shopping Cart" class="butStyle"
44:      onclick="orderItem();location.href='ex07_259620.htm'" />
45: <input type="button" value="Reset Boxes" class="butStyle"
46:      onclick="resetBoxes()" />
47: </body>
48: </html>

Apart from the script language in lines 1825, this page should be self-explanatory. The interface consists of one table (five rows by three columns) and two buttons. A screen shot of this example code is shown in Fig. 7.31.

Figure 7.31. ex07-19.htm

graphics/07fig33.jpg


In addition to the script library cookie.js, this page also uses another library called online.js (line 19). We will discuss this program file in more detail later. After the initialization code in line 21, the page tries to obtain the UserName from the local cookie. If the customer is a member of our online shopping site, the cookie name UserName should be nonzero. Our page will target this customer and offer him or her a good discount. For simplicity, our initialization code will make sure that we have a customer called "John Smith Junior." After he has picked some items from the shopping list and pressed the Shopping Cart button, the selected items will be stored as cookies. A new page ex07-20.htm needs to be activated to display the shopping cart (see Fig. 7.32).



Example: ex07-20.htm - A Page For Order Confirmation

 1: <?xml version="1.0" encoding="iso-88591"?>
 2: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 3:     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 5: <head><title>Online Shopping Confirmation - ex07-20.htm </title></head>
 6: <style>
 7:   .tx01{background-color:#000088;font-family:arial;font-size:13pt;
 8:      font-weight:bold;color:#ffff00;text-align:left}
 9:   .tx02{font-size:18pt;color:#00ffff}
10:   .butStyle{background-color:#aaffaa;font-family:arial;font-weight:bold;
11:      font-size:12pt;color:#008800;width:160px;height:28px}
12: </style>
13:
14: <body class="tx01" style="text-align:center">
15: <script src="cookie.js"></script>
16: <script src="online.js"></script>
17:
18:   <span class="tx02">Order Confirmation</span><br />
19:   <img src="line1.gif" width="480" height="6" /><br /><br />
20:
21:   <script>showCookieTable()</script><br />
22:
23:   <img src="line1.gif" width="480" height="6" />
24:   <div class="tx01" style="color:#00ff00;text-align:center">
25:      Delivery Term: Within 7 Days</div><br />
26:
27: <input type="button" value="Continue Shopping"
28:    class="butStyle" onclick="location.href='ex07_259619.htm'" />
29: <input type="button" value="Cancel Order" class="butStyle"
30:    onclick="delOrders();location.href='ex07_259620.htm'" /><br />
31: </body>
32: </html>

Figure 7.32. ex07-20.htm

graphics/07fig34.jpg


The main part of this page is the library function showCookieTable() in line 21. As mentioned earlier, this function is used to display all cookies on the screen. We will make some improvements to this function later. If the customer clicks the Continue Shopping button (lines 2728), this page will jump back to the previous page ex07-19.htm. If the user clicks the Cancel Order button (lines 2930), the script function delOrders()in online.js is called and all shopping records are destroyed. Let's now take a look at the main program file online.js in more detail.

7.5.2 Constructing the program file

Online shopping usually involves customer information (userInfo), shopping items (goodsName), and prices (goodsPrice). These can be implemented in the main program online.js as arrays. Consider the first part of the main program:



Example: online.js - The ECMAScript For Online Shopping (Part One)

 1: userInfo=Array("UserName","Email Address",
 2:                "ShoppingId","Date&Time")
 3: userInfoLength = userInfo.length
 4:
 5: goodsName=Array("Color Laser Printer","CD-RW(20x20x60)",
 6:                 "Digital Camera","Monitor (19 inch)")
 7: goodsLength=goodsName.length
 8:
 9: goodsPrice=Array(400,100,100,170)
10:
11: goodsId=Array("prt","cdrw","cam","mon")

The most important line of code is line 11. The goodsId is an array representing each of the checked boxes used in the interface (ex07-19.htm). This is the bridge between our programming and the interface. The first function in this program file is initialization initialAll().



Listing: Continuation Of The ECMAScript online.js (Part Two)

12:
13: function initialAll()
14: {
15:  expDate = new Date
16:  expDate.setTime(expDate.getTime()+(1000 * 60 * 60 * 24*365))
17:  setCookie("UserName","John Smith Junior",expDate)
18:  setCookie("Email Address","JohnSmith@isp.com",expDate)
19:  setCookie("ShoppingId","aa0811345678",expDate)
20:  window.resizeTo(620,560)
21: }
22:

This function, as mentioned earlier, is used to make sure that the information of a customer such as name, email address, and a shopping identity is obtained. Line 20 is to resize the window so that the layout and overall display are under control. The next part is the function resetBoxes() to uncheck all checkboxes.



Listing: Continuation Of The ECMAScript online.js (Part Three)

23:  function resetBoxes()
24:  {
25:   for (ii=0;ii<goodsLength;ii++)
26:   {
27:     document.getElementById(goodsId[ii]).checked=0
28:   }
29:  }
30:

This function is called when the Reset Boxes button in ex07-19.htm is pressed. As you can see, this function contains a simple for-loop over all shopping items and hence the checkboxes. The goodsId[ii] in line 27 is used to identify the checkbox and uncheck it. The next part is our main shopping cart function called orderItem().



Listing: Continuation Of The ECMAScript online.js (Part Four)

31:  function orderItem()
32:  {
33:   currentT = new Date
34:   expDate = new Date
35:
36:   expDate.setTime(expDate.getTime() +(1000 * 60 * 60 * 24*365))
37:   setCookie("Date&Time",currentT,expDate)
38:   for (ii=0;ii<goodsLength;ii++)
39:   {
40:     if (document.getElementById(goodsId[ii]).checked)
41:         setCookie(goodsName[ii],goodsPrice[ii],expDate)
42:     else delCookie(goodsName[ii])
43:   }
44:
45:  }
46:

When the user presses the Shopping Cart button in ex07-19.htm, this function will reset the Date&Time variable as in line 37. The next step (lines 3843) is to run through a loop over each checked box. If the checkbox is checked (line 40), the item name and price are stored as cookies (line 41). If the checkbox is unchecked, the cookie is deleted in line 42. When this function returns, the page in ex07-19.htm will jump to the page ex07-20.htm to display the result. The final function in the library provides a cancellation of all items in the shopping cart.



Listing: Continuation Of The ECMAScript online.js (Part Five)

47:  function delOrders()
48:  {
49:   for (ii=0;ii<goodsLength;ii++)
50:   {
51:     delCookie(goodsName[ii])
52:   }
53:  }
54:

When the Cancel Order button is pressed, this function is called. All cookies related to goodsName[] will be destroyed by the for-loop defined in lines 4952.

This working Web program on the shopping cart offers only basic operations. It is time to consider some modifications and improvements.

7.5.3 Improvements and modifications

When you finish a working program, it is good practice to write down any further ideas and thoughts that could improve your Web page. As a simple example, two improvements to page ex07-19.htm are introduced.

  • The ability to trace members of our shopping site and ensure that only members can buy online.

  • Always remember the items in the shopping cart.

These improvements require some modifications to our earlier page ex07-19.htm. One of the modified versions is ex07-21.htm and the body part of this page is listed in ex07-15.txt.



Listing: ex07-17.txt - Code Fragment Of ex07-21.htm

 1: <body class="tx01" style="text-align:center">
 2: <span class="tx02">Today's Special Buy</span><br />
 3: <img src="line1.gif" width="450" height="6" /><br /><br />
 4:
 5: <script src="cookie.js"></script>
 6: <script src="online.js"></script>
 7: <script>
 8:   var disableFlag = 0
 9:   userName = getCookie("UserName")
10:   shopId = getCookie("ShoppingId")
11:   if ((userName != null) && (shopId !=null))
12:   {
13:     outMsg="For: "+userName+" (Half Price!)"
14:   }
15:   else
16:   {
17:     outMsg="Please Set Up An Account First"
18:     disableFlag=1
19:   }
20:   document.write(outMsg)
21:   window.resizeTo(620,550)
22: </script><br /><br />
23:
24: <table border="0" align="center"><tr align="center">
25:     <td width="200">Description</td><td width="120">Price (USD)</td>
26:     <td width="150">Put To <br /> Shopping Cart</td></tr>
27:   <tr align="center"><td>Color Laser Printer</td><td>400</td>
28:     <td><input style="height:25px;width:65px"
29:           type="checkbox" id="prt" name="prt" /></td></tr>
30:   <tr align="center"><td>CD-RW (20x20x60)</td><td>100</td>
31:     <td><input style="height:25px;width:25px"
32:           type="checkbox" id="cdrw" /></td></tr>
33:   <tr align="center"><td>Digital Camera</td><td>100</td>
34:     <td><input style="height:25px;width:25px"
35:           type="checkbox" id="cam" /></td></tr>
36:   <tr align="center"><td>Monitor (19 inch)</td><td>170</td>
37:     <td><input style="height:25px;width:25px"
38:           type="checkbox" id="mon" /></td></tr>
39: </table><br />
40: <input type="button" value="Shopping Cart" class="butStyle" id="but01"
41:      onclick="orderItem();location.href='ex07-22.htm'" />
42: <input type="button" value="Reset Boxes" class="butStyle" id="but02"
43:      onclick="resetBoxes()" />
44:
45: <script>
46:   if (disableFlag ==1) disableAll()
47:   recallOrders()
48: </script>
49: </body>

The basic modifications are lines 821. First, a test is run to see whether the local system has a UserName and ShoppingId as cookies. If no such cookie exists, the system outputs a message to ask the user to set up an account first before shopping. This page sets the disableFlag variable to true (line 18). This disableFlag variable is used in line 46 to disable all checked boxes and buttons. Note that two button identities are added in lines 40 and 42, so that these buttons can be disabled too. A function recallOrders() is also added in line 47 to always remember the items in the shopping cart and set the checked boxes appropriately.

The program file online.js is expanded to include these two newly added functions.



Listing: ex07-16.txt - Continuation Of The ECMAScript online.js (Part Six)

55: function disableAll()
56: {
57:   for (ii=0;ii<goodsLength;ii++)
58:   {
59:     document.getElementById(goodsId[ii]).disabled=1
60:   }
61:   document.getElementById("but01").disabled=1
62:   document.getElementById("but02").disabled=1
63: }
64:
65:  function recallOrders()
66:  {
67:   for (ii=0;ii<goodsLength;ii++)
68:   {
69:    if (getCookie(goodsName[ii])!=null)
70:      document.getElementById(goodsId[ii]).checked=1
71:   }
72: }
73:

The disableAll() function in lines 5563 is simply a loop to disable all checked boxes. Along with the checked boxes, a feature to disable all buttons is added so that no user actions are accepted. The second function recallOrder() is a loop to run through the stored cookies. If the cookie is not empty, the function sets the associated checkbox to true. Put this function into page ex07-21.htm; the page can always remember the items in the shopping cart. The disable feature of this example is illustrated in Fig. 7.33.

Figure 7.33. ex07-21.htm

graphics/07fig35.jpg


Recall from the beginning of section 7.4 that the implementations of cookies are different for different browsers. For instance, one major difference between IE and NS on cookies is the way they store and retrieve cookie information. This may affect the displaying order on screen when calling our library function showCookieTable(). To overcome this problem, you may need to write another displaying function to show cookies in the way you want. Since we use an array to program our shopping cart, overcoming this problem is not difficult. First, you need to modify the interface page ex07-20.htm as ex07-22.htm. The body part of this example is listed below.



Listing: ex07-17.txt - Code Fragment Of ex07-22.htm

 1: <body class="tx01" style="text-align:center">
 2: <script src="cookie.js"></script>
 3: <script src="online.js"></script>
 4:
 5:   <span class="tx02">Order Confirmation</span><br />
 6:   <img src="line1.gif" width="480" height="6" /><br /><br />
 7:
 8:   <script> showGoodsTable() </script><br />
 9:
10:   <img src="line1.gif" width="480" height="6" />
11:   <div class="tx01" style="color:#00ff00;text-align:center">
12:      Delivery Term: Within 7 Days</div><br />
13:
14: <input type="button" value="Continue Shopping"
15:    class="butStyle" onclick="location.href='ex07_259621.htm'" />
16: <input type="button" value="Cancel Order" class="butStyle"
17:    onclick="delOrders();location.href='ex07_259622.htm'" /><br />
18: </body>

In this example, we have changed the old calling function showCookieTable() to showGoodsTable(). This function is incorporated inside our program file online.js.



Listing: ex07-18.txt - Continuation Of The ECMAScript online.js (Part Seven)

74: function showGoodsTable()
75: {
76:  var localMsg=""
77:  var goodsTable=""
78:
79:   for (ii=0; ii<userInfoLength; ii++)
80:   {
81:    varSt = getCookie(userInfo[ii])
82:    if (varSt !=null)
83:    {
84:     localMsg=localMsg+"<tr><td width='150' align='left'>"+
85:        userInfo[ii]+"</td>"+
86:        "<td width='300' align='left'>"+
87:        varSt+"</td></tr>"
88:    }
89:   }
90:
91:   for (ii=0; ii<goodsLength; ii++)
92:   {
93:    varSt = getCookie(goodsName[ii])
94:    if (varSt !=null)
95:    {
96:     localMsg=localMsg+"<tr><td width='150' align='left'>"+
97:        goodsName[ii]+"</td>"+
98:        "<td width='300' align='left'>"+
99:        varSt+"</td></tr>"
100:    }
101:   }
102:   goodsTable="<div align='center'><table>"+localMsg+"</table></div>"
103:   document.write(goodsTable)
104:  }
105:

The layout and rearrangement of orders are handled through the loops in lines 7989 and lines 91104. Figure 7.34 is the screen shot showing how this page works in NS6.x.

Figure 7.34. ex07-22.htm on NS

graphics/07fig36.jpg


With examples ex07-17.htm, ex07-19.htm, and ex07-21.htm, we have some background knowledge (or a basic prototype) of online shopping. Online shopping and security will be discussed further in Part V of this book.

    Table of Contents

    Previous Next