Making a simple AJAX shopping cart

AID: 3255
  • Status: Published

3620 points

  • ByNurAzije
  • TypeTutorial
  • Posted on2010-06-14 at 06:26:14
Making a simple AJAX shopping cart
Couple years ago I made my first shopping cart, I used iframe and JavaScript, it was very good at that time, there were no sessions or AJAX, I used cookies on clients machine.

Today we have more advanced technology, faster, better and more fancy, we can make shopping carts on any site with no need to talk with cookies, let sessions do the storing and AJAX make the communication.

In this tutorial I will show you how to make a Session/AJAX based shopping cart with the usage of WhizBase, If you want more information about WhizBase please read my previous articles at http://www.whizbase.com/eng/?p=8

The products page
Every shopping site have a product page, and that page is where everything starts when you make a shopping. To add products to the shopping cart we need products, every product need an Unique ID. On this page we will also show the cart, we make sure when the visitor comes for the first time it will be empty. Every visit will be a unique shopping and that means a unique session. Sessions are temporary data files created on the server having some data about or from the visitor coming on the site. Every visitor have its own unique session. WhizBase manages sessions automatically, so you just work with session variables as you work with any other, no need to work with session files on the server.

In this file which I will name as «default.wbsp» I will turn sessions to «True» because they are «False» by default. I will also need the AJAX script, the products listings and the shopping cart div.

Look at the code comments for more details:

[FormFields]
WB_UseSessions=T 
#* I am setting WB_UseSessions to True so I can use sessions with WhizBase *#
<!--WB_BeginTemplate-->
#* I am checking if product1,product2 and product3 variables are not set and set a value of zero, that is how I know if the user is comming for the first time or not.*#
$wbif["$wbgets[product1]"=""|$wbsets[product1|0|f]|]$wbif["$wbgets[product2]"=""|$wbsets[product2|0|f]|]$wbif["$wbgets[product3]"=""|$wbsets[product3|0|f]|]
#* I am using $wbgets[varname] to get a session variable, and $wbsets[varname€|value] to set a session variable *#
<html>
<head>
<script type="text/javascript">
#* I am making a showCart JavaScript/AJAx function, it creates an AJAX object and calls «showCart.wbsp» file to show the current status of the cart, the retrieved data is putted by innerHTML into «cartview» div *#
function showCart()
{
  if (window.XMLHttpRequest)
    {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
    }
  else
    {
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  xmlhttp.onreadystatechange=function()
    {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
      document.getElementById("cartview").innerHTML=xmlhttp.responseText;
      }
    }
  xmlhttp.open("GET","showCart.wbsp?rand="+Math.floor(Math.random()*99999999999),true);
  xmlhttp.send();
}

#* addCart function in JavaScript will pass an ID and send it to addCart.wbsp which adds a new product in the cart. On responce we will refresh the cart view by calling showCart function*#

function addCart(id)
{
  if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
    }
  else
    {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  xmlhttp.onreadystatechange=function()
    {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
        showCart();
      }
    }
  xmlhttp.open("GET","addCart.wbsp?id="+id+"&rand="+Math.floor(Math.random()*99999999999),true);
  xmlhttp.send();
}

#* remove function in JavaScript will pass an ID and send it to removeCart.wbsp which removes one product passed from the cart. On responce we will refresh the cart view by calling showCart function  *#

function remove(id)
{
  if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
    }
  else
    {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  xmlhttp.onreadystatechange=function()
    {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
        showCart();
      }
    }
  xmlhttp.open("GET","removeCart.wbsp?id="+id+"&rand="+Math.floor(Math.random()*99999999999),true);
  xmlhttp.send();
}
</script>
</head>
<body onload="showCart();"> 
#* OnLoad we will refresh the cart by showCart() function, this will update the cart div every time we refresh the page *#
#* We list the products and every product have its own ID *#
<a href="javascript:void(0);" onclick="addCart(1);">Product 1</a><br />
<a href="javascript:void(0);" onclick="addCart(2);">Product 2</a><br />
<a href="javascript:void(0);" onclick="addCart(3);">Product 3</a><br /><br /><br />
<b>Cart content</b><br />
#* cartview is a div for holding cart data.*#
<div id="cartview">Cart is empty!</div>
</body>
</html>
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:

Select allOpen in new window



Save this code as default.wbsp.

Adding products in the cart
When we make shopping online, sometimes we want to buy more than one instance from a product, for example I want two T-Shirts. As a user I do not want to see a list in my cart like this: T-shirt,T-shirt,Shoes,chocolate. This will confuse me, so I am adding a counter for every product, so it will be 2x T-shirt, 1x Shoes, 1x chocolate. Keep that in mind. In the next file I am working on I will add data to the session. I will receve data by AJAX calls so I do not need any interface. I will need to check which product I will add and that is made by the sent ID.

If an ID is sent I am adding one instance more, so if I have 4 items from product1 it will become 5 items.

See the comments in the code for more details:

[FormFields]
WB_UseSessions=T
#* I am turning the sessions to True *#
<!--WB_BeginTemplate-->
$wbif["$wbv[id]"="1"|$WBSETS[product1|$WBCalc[$WBGETS[product1]+1]|f]|]
$wbif["$wbv[id]"="2"|$WBSETS[product2|$WBCalc[$WBGETS[product2]+1]|f]|]
$wbif["$wbv[id]"="3"|$WBSETS[product3|$WBCalc[$WBGETS[product3]+1]|f]|]
#* I have three cases in my example so I am hard-coding them. I check the ID variable sent by GET or POST by $WBV, if it is equal an ID I have I will set a value of the variable+1 using $WBCalc, $WBSets and $WBGets, if not do nothing *#
                                    
1:
2:
3:
4:
5:
6:
7:
8:

Select allOpen in new window



In more complex examples you can use loops and not hard-coding the code, this is only for tutorial purposes.

Save this code as addCart.wbsp.

Removing products from the cart
If I want to remove an item from the cart I want to remove one instance only not all the items. So as like adding here I am removing.

[FormFields]
WB_UseSessions=T
#* I am turning the sessions to True *#
<!--WB_BeginTemplate-->
$wbif["$wbv[id]"="1"|$WBSETS[product1|$WBCalc[$WBGETS[product1]-1]|f]|]
$wbif["$wbv[id]"="2"|$WBSETS[product2|$WBCalc[$WBGETS[product2]-1]|f]|]
$wbif["$wbv[id]"="3"|$WBSETS[product3|$WBCalc[$WBGETS[product3]-1]|f]|]
#* Removing is the same code as adding but the only different we will remove an item not adding it. *#
                                    
1:
2:
3:
4:
5:
6:
7:
8:

Select allOpen in new window



Save this code as removeCart.wbsp.


Show me my Cart
Finally we will make the showCart.wbsp file, it will just contain some HTML and WhizBase code for showing the cart content.

[FormFields]
WB_UseSessions=T
#* I am turning the sessions to True *#
<!--WB_BeginTemplate-->
There is:
<br />$wbgets[product1] X Product1 $wbif[$wbgets[product1]>0|(<a href="javascript:void(0);" onclick="remove(1);">remove</a>)|] #* we show the session variable containning number of items of the products and only if there is items then show the remove link also *#
<br />$wbgets[product2] X Product2 $wbif[$wbgets[product2]>0|(<a href="javascript:void(0);" onclick="remove(2);">remove</a>)|]
<br />$wbgets[product3] X Product3 $wbif[$wbgets[product3]>0|(<a href="javascript:void(0);" onclick="remove(3);">remove</a>)|]<br />
                                    
1:
2:
3:
4:
5:
6:
7:
8:

Select allOpen in new window



Save this code as showCart.wbsp.

What's next
This is a very simple tutorial to show you how you can make a shopping cart using AJAX/WhizBase technologies. If you want more complex shopping carts you need to use loops and databases which can be also done with WhizBase and AJAX, if you are not familiar with WhizBase please read my previous articles.


For more information email me at: NurAzije [at] Gmail [dot] com Or visit the WhizBase official site at www.whizbase.com

NurAzije is a PHP and WhizBase programmer, who at the time of article publication is working in partnership with WhizBase on several projects.
Asked On
2010-06-14 at 06:26:14ID3255
Tags

AJAX

,

WhizBase

,

Shopping Cart

,

Sessions

,

Scripting Language

Topic

Scripting Languages

Views
3020

Comments

Author Comment

by: NurAzije on 2010-06-14 at 13:30:20ID: 15724

Thank you very much and good luck.

Add your Comment

Please Sign up or Log in to comment on this article.

Join Experts Exchange Today

Gain Access to all our Tech Resources

Get personalized answers

Ask unlimited questions

Access Proven Solutions

Search 3.2 million solutions

Read In-Depth How-To Guides

1000+ articles, demos, & tips

Watch Step by Step Tutorials

Learn direct from top tech pros

And Much More!

Your complete tech resource

See Plans and Pricing

30-day free trial. Register in 60 seconds.

Loading Advertisement...

Top Scripting Languages Experts

  1. mplungjan

    145,789

    Master

    0 points yesterday

    Profile
    Rank: Savant
  2. Ray_Paseur

    91,292

    Master

    0 points yesterday

    Profile
    Rank: Savant
  3. billprew

    63,376

    Master

    0 points yesterday

    Profile
    Rank: Genius
  4. RobSampson

    54,636

    Master

    0 points yesterday

    Profile
    Rank: Genius
  5. DaveBaldwin

    51,700

    Master

    2,000 points yesterday

    Profile
    Rank: Genius
  6. sedgwick

    43,950

    1,600 points yesterday

    Profile
    Rank: Genius
  7. leakim971

    43,184

    0 points yesterday

    Profile
    Rank: Genius
  8. dgofman

    36,400

    0 points yesterday

    Profile
    Rank: Genius
  9. COBOLdinosaur

    28,424

    0 points yesterday

    Profile
    Rank: Genius
  10. woolmilkporc

    24,200

    0 points yesterday

    Profile
    Rank: Genius
  11. ozo

    20,600

    0 points yesterday

    Profile
    Rank: Savant
  12. Qlemo

    19,984

    2,000 points yesterday

    Profile
    Rank: Genius
  13. chaituu

    19,100

    0 points yesterday

    Profile
    Rank: Sage
  14. tagit

    19,000

    0 points yesterday

    Profile
    Rank: Genius
  15. farzanj

    18,550

    0 points yesterday

    Profile
    Rank: Genius
  16. nap0leon

    15,094

    0 points yesterday

    Profile
    Rank: Sage
  17. paultomasi

    14,700

    0 points yesterday

    Profile
    Rank: Master
  18. StingRaY

    13,136

    0 points yesterday

    Profile
    Rank: Wizard
  19. jason1178

    13,044

    0 points yesterday

    Profile
    Rank: Genius
  20. HainKurt

    12,350

    0 points yesterday

    Profile
    Rank: Genius
  21. HonorGod

    11,600

    0 points yesterday

    Profile
    Rank: Genius
  22. ahoffmann

    11,136

    0 points yesterday

    Profile
    Rank: Genius
  23. basicinstinct

    10,800

    0 points yesterday

    Profile
    Rank: Genius
  24. leew

    10,030

    0 points yesterday

    Profile
    Rank: Savant
  25. ChrisStanyon

    9,864

    0 points yesterday

    Profile
    Rank: Sage

Hall Of Fame