Making a simple AJAX shopping cart

Published:
Updated:
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>
                      

Open 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 *#
                      

Open 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. *#
                      

Open 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 />
                      

Open 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.
1
6,255 Views

Comments (1)

Author

Commented:
Thank you very much and good luck.

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.