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

20.3 Implementation of an online bargain hunting shop

Table of Contents

Previous Next

20.3 Implementation of an online bargain hunting shop

20.3.1 Getting user information with cookies and a database

There are a number of ways to implement a shopping-cart feature for an online shop. In fact, you developed an elementary implementation in Chapter 7. To simply our approach, we are going to use all the ECMAScript functions developed in section 7.4 and included in the libraries



cookie.js and online.js

These two libraries provide all ECMAScript functions that we need to handle cookies. In order to make the shopping cart in Chapter 7 more practical and more suitable for our online bargain shop, the following database features are added:

  • Obtain user information from the database and pass them to the shopping cart of the shop.

  • Develop an online shopping catalog with a database table so that changes can be made rapidly and easily.

Other features of the shopping cart parallel the examples in Chapter 7.

One of the beauties of using database features is that once you have done all the design and programming, you can add more items or change prices, product descriptions, and even product pictures easily. In many cases, you don't need to touch your XHTML coding or pages at all!

As we mentioned in Chapter 7, most shopping cart implementations use cookies. In normal circumstances, two sets of cookies are used. One set of cookies is to identify the customer so that charges can be made, the second set of cookies is, obviously, to remember the shopping items in the shopping cart. Usually, the user information cookies are

  • User name

  • Email address

  • Shopping identity

In terms of our user profile in section 20.2.1, this information can be extracted and matched by user identity (userId), encrypted password (i.e., MD string of passId), and email address (email_add).

To use the login example in section 20.2.3 for our shopping site is simple. The first step is to copy the example ex20-05.php to ex20-06.php. The second step is to replace the code after line 14 by the following:



Example: ex20-06.php - Program Fragment For User Login

15: <?php
16: global $llst, $userId, $passId;
17:
18:  $llst = 'Welcome To ABC Online Bargain Hunting<br /> ' .
19:   ' This Is A Member Only Site<br /><br /> ' .
20:   ' Enter User Name and Password To Log In<br />' .
21:   ' <form action="ex20-06.php" method="post">'.
22:   ' <table class="txtSt">' .
23:   ' <tr><td>Username:</td><td>' .
24:   '  <input type="text" name="userId" id="userId" class="butSt" />' .
25:   '  </td></tr>' .
26:   ' <tr><td>Password:</td><td>' .
27:   '  <input type="password" name="passId" id="passId" class="butSt" />' .
28:   '  </td></tr> ' .
29:   ' <tr><td colspan="2" style="text-align:center"><br />' .
30:   '  <input type="submit" value="Login" class="butSt2" />' .
31:   '  <input type="button" value="Join Member" class="butSt2" '.
32:   '     onclick="location.href=\'ex2003.htm\'" /> </td></tr>' .
33:   ' </table>' .
34:   ' </form> ';
35:
36: if ($passId && $userId)
37: {
38:  $passId = md5($passId);
39:
40:  $db = mysql_connect("www.pwt-ex.com", "johnsmith","johnsmith");
41:  mysql_select_db("buss_db",$db);
42:
43:  $query = "SELECT * FROM cust_profile WHERE user_id='$userId'";
44:  $result = mysql_query ($query) or die ("SQL Query Error..");
45:
46:  $row = mysql_fetch_array ($result);
47:
48:  if (($passId == $row['password']) && ($userId == $row['user_id']))
49:  {
50:    echo"Thankyou $userId! <br /> Enjoy Your Shopping!<br /><br />";
51:    global $userName, $shoppingId, $Id;
52:    $userName = $userId;
53:    $shoppingId = $row['password'];
54:    $emailId = $row['email_add'];
55:    echo('<script>window.location="ex2007.php?name=' . $userName .
56:         '&id=' . $shoppingId . '&em='. $emailId .'"</script>');
57: }
58: else
59: {
60:   echo "$llst";
61:   if ($userId == $row['user_id'])
62:   {
63:     echo "<br />Sorry! Wrong Password.. Please Try Again..<br />";
64:     $passId = false;
65:   }
66:  }
67:  mysql_free_result ($result);
68: }
69: else
70: {
71:    echo "$llst";
72: }
73: ?>
74: <br /><img src="line1.gif" width="500" height="6" alt="pic" />
75: <br /><br />
76: </body>
77: </html>

This page is almost identical to the page ex20-05.php. The only differences are at line 21 and in the program block in lines 4857. Inside this program block is the case when the user name and password match the information in the database. The user name, password, and email address from the database are assigned to the variables $userName, $shoppingId, and $emailId respectively.

Suppose you log in with

User name = johnsmith and Password = johnsmith

then the statement in lines 5556 turns out to be



<script>window.location="ex2007.php?
  name=johnsmith&
  id=cd4388c0c62e65ac8b99e3ec49fd9409&
  em=$johnsmith@pwt-ex.com"
</script>

This statement will activate our main shopping-cart page with name, identity (id), and email (em) as the query string. The query string is passed to the page ex20-07.php as variables. This process is similar to the get method used in an XHTML form. The information is passed to the shopping-cart program and can later be used to identify the user and make charges using the credit card information in the database.

Now let's consider how to use a database to construct an online catalog for our e-commerce site.

20.3.2 Designing an online catalog with a database

If you don't have a database package such as Microsoft Access, MySQL, etc., you can still build and develop your shopping catalog using plain XHTML coding. For example, if you only have a handful of products that you want to sell on the Internet, it may be even easier to hard-code them using XHTML tables similar to the examples in Chapter 7. It is fair to say that as long as you can handle the administrative work of your commercial site, you may be better off without using a database.

On the other hand, if you have a large number of products to sell on the Web, you may need a database approach. Also, if your products change every one or two weeks just like an online bargain hunting shop, you need to consider the use of a database to help you.

Putting items into a database will greatly reduce the administrative and maintenance work. If you are working or want to work for a Web design company, chances are that your company will demand database skills from you.

To use a database for an online catalog is no different from the database applications on people or personnel in Part IV of this book. The basic idea is that product items are stored in the database as records of a table. An XHTML page is then developed to extract the records and display them on the browser window. To simplify the implementation, we only consider the following fields in the database:

  • Product identity (product_id)

  • Product image (product_img)

  • Product description (description)

  • Product price (price)

Suppose you want to set up an online big bargain shop dedicated to members or customers. The shop sells different products at a good discount every week. For this week (e.g., week112), you are selling blank CDs with big savings on quantities. Three products are selected, namely, CD-R, CD-RW, and DVD-R. First, you need to use the SQL statement in ex20-01.txt to create the table for the products.



Listing: ex20-01.txt - Building Catalog With MySQL

1: CREATE TABLE week112
2: (
3:   product_id VARCHAR(20) NOT NULL,
4:   product_img VARCHAR(20) NOT NULL,
5:   description VARCHAR(50) NOT NULL,
6:   price VARCHAR(10) NOT NULL,
7:   PRIMARY KEY(product_id)
8: );

With the MySQL knowledge in Chapters 18 and 19, this SQL statement is easy to understand. The next step is to generate some product data and load them into a table. As a simple example, the product data file week112.dat is listed below:



Example: ex20-02.txt - Data File For E-Commerce (File: week112.dat)

1:   50 CD-R, cdr.gif, 50 CD-R Disc <br /> 1x-16x 74min, 5.50
2:   50 CD-RW, cdrw.gif, 50 CD-RW Disc <br />4x-10x 74min , 7.00
3:   25 DVD-R, dvdr.gif, 25 DVD-R <br />4.7GB , 55.00

The first column is the product identity to identify the items. The second column contains the image files of the product. They are used to display a picture of the product in the catalog. The third column is a description of the product. The new line code <br /> is used to insert a new line when you display the description on a browser window. The final column contains the prices of each product.

Now, you can load the data file week112.dat into the table using the usual LOAD DATA statement below:



LOAD DATA INFILE 'week112.dat'
INTO TABLE week112
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n';

Please note that, if you are using MySQL in Microsoft systems, the last statement above should be replaced by



LINES TERMINATED BY '\r\n';

because every text string in Microsoft systems is terminated by a carriage return ("\r") followed by a new line ("\n"). After the data loading, you can use the following SELECT command to examine the table:



SELECT * FROM week112;

You should see the table with the data as in ex20-03.txt.



Listing: ex20-03.txt - Building Catalog With MySQL

 1: +------------+-------------+----------------------------------+-------+
 2: | product_id | product_img | description                      | price |
 3: +------------+-------------+----------------------------------+-------+
 4: | 50 CD-R    | cdr.gif     | 50 CD-R Disc <br /> 1x-16x 74min | 5.50  |
 5: | 50 CD-RW   | cdrw.gif    | 50 CD-RW Disc<br /> 4x-10x 74min | 7.00  |
 6: | 25 DVD-R   | dvdr.gif    | 25 DVD-R <br />4.7GB | 55.00     |
 7: +------------+-------------+----------------------------------+-------+

20.3.3 Building the shopping-cart page

From the demonstration examples in section 7.4, we know that as long as you can put the product identity, name, price, and picture into ECMAScript arrays such as



<script>
goodsId= Array("50 CD-R","50 CD-RW","25 DVD-R");
goodsName=Array("50 CD-R Disc <br /> 1x-16x 74min",
                "50 CD-RW Disc<br /> 4x-10x 74min",
                  "25 DVD-R <br />4.7GB");
goodsPrice=Array("5.50","7.00","55.00");
goodsPic=Array("cdr.gif","cdrw.gif","dvdr.gif");
</script>

you can use the examples in ex07-19.htm to ex07-22.htm directly to build a shopping cart. More precisely, you can use the functions defined in the ECMAScript files cookie.js and online.js.

The implementations in section 7.5 are independent of any selling products and their descriptions. That is, if you can use the database table in section 20.3.2 and fill up the ECMAScript arrays above, you can modify the examples in section 7.5 (i.e., ex07-19.htm to ex07-20.htm) to develop the shopping cart for the shop.

Basically, the implementation of our shopping-cart page is to extract the product information from the database table week112 to fill up the arrays above. Let's consider the first part of the page:



Example: ex20-07.php - Main Page For The Shopping Cart (Part One)

 1: <?PHP echo"<?";?>xml version="1.0" encoding="iso-88591"<?PHP echo"?>";?>
 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>Shopping Cart - ex2007.php </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:   .chBut{background-color:#aaffaa;font-family:arial;
13:      font-size:18pt;color:#008800;width:50px;height:25px}
14: </style>
15: <body class="tx01" style="text-align:center">
16: <span class="tx02">Today's Special Buy</span><br /><br/>
17: <img src="line1.gif" width="600" height="6" /><br /><br />
18:
19: <script src="cookie.js"></script>
20: <script src="online.js"></script>

This PHP page is simple. The main feature is to include the two ECMAScript files cookie.js and online.js into the program (see lines 1920). These two program files provide all functions that are needed to handle cookies. For a full detailed explanation of these files, see section 7.5.2.

The next step is essential for the entire page. The following tasks are performed:

  • Connect to the database table buss_product and obtain the product information.

  • Use the product information to build the following ECMAScript arrays:

    - goodsId = Array("xxx","xxx",..,"xx");

    - goodsName = Array("xxx","xxx",..,"xx");

    - goodsPrice= Array("xxx","xxx",..,"xx");

    - goodsPic = Array("xxx","xxx",..,"xx");

Each array represents one column in the catalog. For example, the elements in the goodsPic array store the image files of the products and will be displayed as images. Let's consider the PHP program coding for this part:



Listing: Continuation Of The PHP Script ex2007.php (Part Two)

21: <script>
22:   var goodsLength;
23:
24: <?php
25:    $host="www.pwt-ex.com";
26:    $user="johnsmith";
27:    $password="johnsmith";
28:    $databaseName = "buss_db";
29:    $tableName = "week112";
30:
31:    mysql_connect($host,$user,$password);
32:    mysql_select_db($databaseName);
33:    $querySt = "SELECT * FROM " . $tableName;
34:    $result = mysql_query($querySt);
35:    global $gId, $gNa, $gPr;
36:
37:    if ($result == 0)
38:      echo("SQL Query Error..");
39:    else
40:    {
41:     $gId = "goodsId=Array(";
42:     $gNa = "goodsName=Array(";
43:     $gPr = "goodsPrice=Array(";
44:     $gPic = "goodsPic=Array(";
45:     $count = mysql_num_rows($result);
46:     for ($ii = 0; $ii < $count-1; $ii++)
47:     {
48:        $row = mysql_fetch_array ($result);
49:        $gId = $gId . '"' . $row['product_id'] . '",';
50:        $gNa = $gNa . '"' . $row['description'] . '",';
51:        $gPr = $gPr . '"' . $row['price'] . '",';
52:        $gPic = $gPic . '"' . $row['product_img'] . '",';
53:     }
54:        $row = mysql_fetch_array ($result);
55:        $gId = $gId . '"' . $row['product_id'] . '");';
56:        $gNa = $gNa . '"' . $row['description'] . '");';
57:        $gPr = $gPr . '"' . $row['price'] . '");';
58:        $gPic = $gPic . '"' . $row['product_img'] . '");';
59:    }
60:    echo($gId);
61:    echo($gNa);
62:    echo($gPr);
63:    echo($gPic);
64: ?>
65:

Since PHP is a server script, it can be used to generate ECMAScript and executed by the calling browser. First, lines 2532 are used to connect to the database buss_db and table week112. After execution of the SQL statement, the information on the products is stored in the variable $result as illustrated in line 34. The next step is to define four variables, $gId (goods identity), $gNa (goods name), $gPr (goods price), and $gPic (goods picture). These variables are used to build the desired ECMAScript arrays. The actual building process is no more than a series of string concatenation operations. Lines 4144 are used to build the starting string. The for-loop in lines 4653 simply fetches each row of the database table and fills the arrays with product items. Lines 5458 are used to put the finishing touches to the arrays. The contents of the variables are listed below:



$gId -- goodsId= Array("50 CD-R","50 CD-RW","25 DVD-R");
$gNa -- goodsName=Array("50 CD-R Disc <br /> 1x-16x 74min",
                        "50 CD-RW Disc<br /> 4x-10x 74min",
                        "25 DVD-R <br />4.7GB");
$gPr -- goodsPrice=Array("5.50","7.00","55.00");
$gPic -- goodsPic=Array("cdr.gif","cdrw.gif","dvdr.gif");

The echo statements in lines 6063 output the variables to the browser and ultimately define the arrays using ECMAScript.

Now, if you want to change the prices of the products, you can change the data inside the table week112 using SQL statements without even touching any XHTML coding.

For the next bargain week, all you have to do is to design the week113 data file (e.g., week113.dat) similar to ex20-02.txt and to generate a new table as in ex20-03.txt. Don't forget to change the database table name $tableName in line 29 of ex20-07.php so that the page can recognize the changes to the data.

Now we have the shopping items under control. Our next task is to identify the individual who is doing the shopping. For this purpose, you need to capture the user information submitted from the login page ex20-06.php and store the customer information as cookies. Consider the third part of ex20-07.php below:



Listing: Continuation Of The PHP Script ex2007.php (Part Three)

66:  userInfo=Array("UserName","Email Address","ShoppingId","Date&Time")
67:
68:  userInfoLength = userInfo.length
69:  goodsLength=goodsName.length
70:  function initialAll()
71:  {
72:   expDate = new Date
73:   expDate.setTime(expDate.getTime()+(1000 * 60 * 60 * 24*365))
74: <?php
75:   echo(' setCookie("UserName","' . $name .'",expDate);');
76:   echo(' setCookie("Email Address","' . $em .'",expDate);');
77:   echo(' setCookie("ShoppingId","' . $id .'",expDate);');
78: ?>
79:
80:  }
81: </script>
82:

The main feature of this page is the ECMAScript function initialAll() defined in lines 7081. Inside this function, a small PHP code is used to capture the user name ($name), email address ($em), and shopping identity ($id) from the login page.

Suppose you log in with

User name = johnsmith and Password = johnsmith

The initialAll() function turns out to be



function initialAll()
{
 expDate = new Date
 expDate.setTime(expDate.getTime()+(1000 * 60 * 60 * 24*365))
 setCookie("UserName","johnsmith",expDate);
 setCookie("Email Address","johnsmith@pwt-ext.com",expDate);
 setCookie("ShoppingId","cd4388c0c62e65ac8b99e3ec49fd9409",expDate);
}

Obviously, the shopping identity (ShoppingId) of the user is actually the MD string returned from the login page representing the password johnsmith. If this function is called, it will set the user name, email address, and shopping identity information as cookies.

You now have everything you need to develop an interface page to show the online catalog. Consider the fourth part coding of the example:



Listing: Continuation of Example ex20-07.php (Part Four)

83: <script>
84:   initialAll()
85:   userName = getCookie("UserName")
86:   outMsg="For: "+userName+" (Half Price!)"
87:   document.write(outMsg)
88: </script><br /><br />
89:
90: <script>
91:  tableSt ='<table cellspacing="10" align="center" class="tx01">'+
92:           '<tr align="center">'
93:  tableSt += '<td>Picture </td><td>Description</td>'+
94:             '<td>Price </td><td>Add To <br /> Shopping Cart</td></tr> '
95:
96: for (ii = 0; ii< goodsLength; ii++)
97: {
98:  tableSt += '<tr align="center">' +
99:      '<td><img src="'+goodsPic[ii]+'" width="70" height="60" /></td>'+
100:      '<td>'+goodsName[ii]+'</td><td>'+goodsPrice[ii]+'</td> '+
101:      '<td><input style="height:35px;width:35px" '+
102:            'type="checkbox" id="'+ goodsId[ii]+'" /></td></tr> '
103:  }
104:  tableSt +='</table><br />'
105:  document.write(tableSt)
106: </script>
107:
108: <img src="line1.gif" width="600" height="6" /><br /><br />
109: <input type="button" value="Checkout" class="butStyle"
110:      onclick="orderItem();location.href='ex20-08.htm'" />
111: <input type="button" value="Reset Boxes" class="butStyle"
112:      onclick="resetBoxes()" />
113:
114: </body>
115: </html>

The first part of this code fragment (lines 8388) is to call the function initialAll() to set up the user information as cookies. Then a welcome message to the user is displayed.

To build the catalog, a single XHTML table which is defined as an ECMAScript string called tableSt is used. Lines 9194 define a table row for the headings of the catalog which include the "Picture," "Description," "Price," and "Add to Shopping Cart."

The for-loop in lines 96103 simply fills the rows of the table with product information. Note that product information is now stored in the ECMAScript arrays goodsPic[], goodsName[], goodsPrice[]. Also, we have used a checkbox to indicate whether the product is added to the shopping cart. For commercial applications, you may want to enhance this facility by adding buttons, quantities, and many other features including all kinds of cookie administration as illustrated in Chapter 7. A checkbox is considered to be a simple solution for our demonstration purposes as the user can always see what he or she has ordered at any time just by taking a look at the box. Line 104 puts the finishing touch to the table and the next line is to output the table to the browser window.

When the user has picked something and is satisfied with what he or she wants to buy, a Checkout button (lines 109110) is ready for him or her to proceed. Once this button is clicked, the ECMAScript function orderItem() is called. This function is located in the script file online.js. The main purpose of this function is to set all the selected items as cookies on the user's machine. Therefore we have all the cookies about the user and products ready. Now control is transferred to the checkout page as illustrated by the script statement location.href='ex2008.htm' at the end of line 110.

Some screen shots of this example are shown in Figs 20.5 and 20.6.

Figure 20.5. ex20-06.php

graphics/20fig05.jpg


Figure 20.6. ex20-07.php

graphics/20fig06.jpg


Another feature of this example is the use of PHP to control the database and ECMAScript to implement the cookie part. The bridge is performed by some ECMAScript arrays such as goodsName, goodsId, etc. No matter what kind of server database technologies you are using, the program will work fine if your database can fill up the arrays consistently. This feature would enhance the portability and reusability of your program code in some ways. Also, as a good Web engineer, you should be able to integrate or mount two technologies together at any time if necessary.

Now it's time to take a look at the checkout facilities of our shop.

20.3.4 A checkout facility

For obvious reasons our checkout facility can only be a simple one. Even a minimal checkout should include the following functionalities:

  • Display all selected items from the cookies so that the customer knows the items, price, delivery terms, and other information.

  • Include a Cancel button so that cancellation can be made at the last minute.

  • Include a Confirm button to confirm the order.

  • If the Confirm button is clicked, a permanent record of the order should be saved on the server so that charges can be made later using the member's credit card information.

  • Delete all cookies as soon as possible.

Since ECMAScript is used to implement cookies, the main page of this checkout facility is coded by XHTML. The first part of the page is listed below:



Example: ex20-08.htm - A Checkout Page (Part One)

 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> Checkout Page  ex2008.htm</title></head>
 6: <style>
 7:   .tx01{background-color:#000088;font-family:arial;font-size:14pt;
 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: <body class="tx01" style="text-align:center">
14: <span class="tx02">Order Confirmation</span><br />
15: <img src="line1.gif" width="480" height="6" /><br /><br />
16: <script src="cookie.js"></script>
17: <script src="online.js"></script>
18: <script>
19:   var cookieN = new Array()
20:   var cookieV = new Array()
21:   var cookieL
22:  function showSelectedItem()
23:  {
24:   var localMsg="<table class='tx01'>"
25:   var cookieTable=""
26:   if (document.cookie !="")
27:   {
28:    var cookieItem = document.cookie.split("; ")
29:    cookieL = cookieItem.length
30:    for (i=0; i< cookieItem.length; i++)
31:    {
32:      cookieN[i] = cookieItem[i].split("=")[0]
33:      cookieV[i] = unescape(cookieItem[i].split("=")[1])
34:
35:      localMsg += "<tr><td width='150' align='left'>"+
36:                    cookieN[i]+"</td>"+
37:                   "<td width='300' align='left'>"+
38:                    cookieV[i]+"</td></tr>"
39:     }
40:     cookieTable="<div align='center'>"+localMsg+"</table></div>"
41:     document.write(cookieTable)
42:   }else
43:    document.write("There Is No Selected Item")
44:  }
45: showSelectedItem()
46: </script><br />
47: <img src="line1.gif" width="480" height="6" />
48: <div class="tx01" style="color:#00ff00;text-align:center">
49:      Delivery Term: Within 7 Days</div><br />
50:

To display all selected items (or cookies) on the browser window, a script function called showSelectItem() is developed in lines 2244. If there is no cookie on the local machine, the message in line 43 is displayed. If the cookie string is not empty (see line 26), we want to build a simple table to display all of them. Since cookies are stored as a string separated by semi-colons (";"), the function in line 28



cookieItem = document.cookie.split("; ")

is used to separate them one by one into collection cookieItem. Each cookieItem contains a name/value pair with an equals ("=") sign. To separate them further, the following split functions are used (see lines 3233) to store the name/value pair into two arrays:



cookieN[i] = cookieItem[i].split("=")[0]
cookieV[i] = unescape(cookieItem[i].split("=")[1])

These two arrays are then used to build the contents of an XHTML table as illustrated in lines 3538. At the end the cookieTable is built and output to the browser in line 41.

The showSelectedItem() function is called in line 45 so that the user can see all the selected items on the screen. At the end of this code fragment, the delivery terms are also displayed (see lines 4849).

To implement the Confirm and Cancel buttons for our checkout, consider the following example code:



Listing: Continuation of Example ex20-08.htm (Part Two)

51: <form method="post" action="ex20-09.php">
52: <script>
53:   var lst = '<input type="hidden" name="itemL" value="'+cookieL+'" />'
54:   for (ii = 0; ii < cookieL; ii++)
55:   {
56:      lst += '<input type="hidden" name=selItem[]'+
57:             ' value="'+ cookieN[ii]+' = ' + cookieV[ii] +'" />'
58:   }
59:   document.write(lst);
60: </script>
61: <input type="button" value="Confirm Order" class="butStyle"
62:    onclick="delAllCookies();submit()" />
63: <input type="button" value="Cancel Order" class="butStyle"
64:    onclick="delAllCookies();location.href='ex20-10.htm'" /><br />
65: </form>
66: </body>
67: </html>

This is a form application containing two buttons. The contents of the form are built by a for-loop (lines 5458) making a series of input elements with cookie names and values. The type of each input element is hidden so that it will not display to the user. Also, we use an array called selItem[] as the name of the input element so that the entire array will be passed to the form action program.

The purpose of this arrangement is that when the Confirm Order button in line 61 is clicked, these input elements are submitted as data to an order confirmation page. Inside this confirmation page, the selected items will be saved as permanent records. Any server script with file-handling capabilities such as Perl, ASP (or ASP.NET), and PHP can do that. In this example, we use a PHP script ex20-09.php to perform the file operation.

Since we want to delete all cookies as soon as possible, the delAllCookies() function is called before the form submission in line 62. If the Cancel Order button is clicked, all cookies will be deleted and perform a jump to the cancellation page ex20-10.htm as illustrated in line 64.

First, consider the order confirmation page ex20-09.php below:



Example: ex20-09.php - The Order Confirmation Page

 1: <?PHP echo"<?";?>xml version="1.0" encoding="iso-88591"<?PHP echo"?>";?>
 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 - ex2009.php</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: </style>
11: <body class="tx01" style="text-align:center"><br /><br />
12:
13:   <span class="tx02">Order Confirmed. <br />Thank you ! <br /><br /><br />
14:    We Will Deliver Your <br />Order Within 7 Days</span><br />
15:
16: <?php
17:  $filename = "ordering.txt";
18:  $fd = fopen ($filename, "a");
19:
20:  for ($ii=0; $ii < $itemL ; $ii++)
21:  {
22:    $llst = $selItem[$ii] . "\n";
23:    fwrite ($fd, $llst);
24:  }
25:    fwrite($fd,"=======================================\n");
26:    fclose ($fd);
27: ?>
28: </body>
29: </html>

This is a simple PHP page to perform file operations. Recall that example ex20-08.htm submitted one variable $itemL (i.e., item length) and one array $selItem[] (i.e., selected items) to this program through the form action. The array stores all items ordered by the customer and needs to be saved into a file as a permanent record. In order to do that, the PHP program block in lines 1627 is implemented.

First, you can assign a file name to the variable $filename. The next step is to open the file with append mode so that a new purchase order is appended at the end of the file. The for-loop in lines 2024 is to write the elements of the array $selItem[] into the file one by one.

The purpose of using a new string variable $llst in line 22 is to add a new line symbol ("\n") at the end of the element $selItem[] so that the string $llst contains a new line character. When this string is written into a file by the statement in line 23, it will occupy one line. If you are using Microsoft systems, you should use the following:



$llst = $selItem[$ii] . "\r\n";

When all ordered items have been written to the file, the file is closed with a separation line as illustrated in lines 2526. Since file operations are transparent to the end user, a simple message is displayed in lines 1314 to confirm the order. A screen shot of example ex20-08.htm is shown in Fig. 20.7. The permanent record of the online order file (i.e., ordering.txt) is shown in Fig. 20.8.

Figure 20.7. ex20-08.htm

graphics/20fig07.jpg


Figure 20.8. The contents of the file ordering.txt

graphics/20fig08.jpg


When used with the user profile, the ordering.txt file should be able to provide charging information for your customer.

Finally, if the Cancel Order button is clicked, a cancel page (ex20-10.htm) is activated. This is a very simple XHTML page. For completeness of the example, this page is listed as follows:



Example: ex20-10.htm - The Order Cancellation Page

 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> Order Cancellation Page - ex0810.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: </style>
11: <body class="tx01" style="text-align:center"><br /><br />
12:   <span class="tx02">Your Order ! <br /><br /><br />
13:    Has Been Cancelled.</span><br /><br />
14: <img src="line1.gif" width="500" height="6" alt="pic" /><br />
15: </body>
16: </html>

Now it's time to discuss some serious security measures on the Web that can provide security and transparency between your customers and your e-commerce site(s).

    Table of Contents

    Previous Next