How to create an ajax powered cart system

The title might sound familiar. Its because there are already lots of tutorials on this topic before. Here are some of them:

Developing an ajax driven shopping cart with PHP and Prototype

Build an ajax powered shopping cart

Shopping cart php jquery


You might want to check out one of those before coming here. I recommend that you check the one from nettutsplus, its an in-depth tutorial on making an ajax powered cart.


  • Wampserver
  • Jquery core



Okay, seems like you’re still here after having me linking to some good content. So let’s not waste time and let’s get started. But before that, here’s a sample output. The list of products:


And the interface where the user can edit the quantity for each product. Any of the added products can also be removed and the grand total will automatically be updated.


First you’ll have to prepare your database and the directory that you’re going to work with. If you want to use the table that I’m using, you can go ahead and execute this query on phpmyadmin or the mysql console. Just make sure that you have already created a database before doing so. Because the query below is just use for creating table and putting some sample data.

  `product_id` int(11) NOT NULL AUTO_INCREMENT,
  `product_name` varchar(100) NOT NULL,
  `quantity` int(11) NOT NULL,
  `price` double NOT NULL,
  PRIMARY KEY (`product_id`)

-- Dumping data for table `products`

INSERT INTO `products` (`product_id`, `product_name`, `quantity`, `price`) VALUES
(1, 'guava', 300, 200),
(2, 'melon', 200, 30),
(3, 'apple', 10, 2),
(4, 'papaya', 300, 700);

Next, create a new php file. This will be the one that were going to use as the main file for user interactions. In short this is where we will put most of the html.
As usual you need to include your database configuration file and the jquery  file. You can also put it on the same file if you like.

<?php require_once('pos_config.php'); ?>


<script src="jq.js"></script>

Next, perform a query that will fetch all the products from the table. Yes, this tutorial is pretty much in its simplest form. As much as possible I don’t want to add more functionalities. Just the core functionalities of a cart system is enough.

$fetch = $db->get_results("SELECT * FROM products");

<div id="prodlist">
<table border="1">
	<th>Add to Cart</th>
<?php foreach($fetch as $k=>$f){?>
<tr id="<?php echo $k; ?>">
	<td><?php echo $f->product_name; ?></td>
	<td><?php echo $f->price; ?></td>
	<td><img src="add.png" class="addtocart" data-prod="<?php echo $f->product_name; ?>" data-price="<?php echo $f->price;?>" id="<?php echo $f->product_id; ?>"></img></td>
<?php } ?>
<input type="button" id="btn_confirm" value="Confirm Selection">

Yup that’s easy enough if you’re already doing CRUD since you were an infant. But if that didn’t make sense to you then here’s what it does:

First we created a div that will contain the table of products that was fetched from the database. I put it inside a div because were going to hide that div later on once the selection of products to be both has been confirmed by the user. Then we just loop through the contents of the variable $fetch which contains an array of product names and prices.
Then in the add to cart button we added 3 attributes which is primarily used for storing data:

  • id – contains the unique product id, this will be used as a key.
  • data-prod – contains the product name
  • data-price – contains the price of the product

Lastly we have a button with the id attribute of btn_confirm. Which we will use to hide the product list once the list of products to be added to cart is confirmed by the user.

Next, add another div. This is where we will put all of the products that the user adds to the cart.

<div id="added">
   <!--products added to cart goes here-->

Next, go to the head section of your file and do the jquery housekeeping procedure:

    //magic happens here

Next, the action that we need to perform once the user clicks on any of the add to cart buttons.

	var prod_id = $(this).attr('id');
	var price = $(this).attr('data-price');
	var prod = $(this).attr('data-prod');
	$('#added').load('session_creator.php', {'prodid' : prod_id, 'price' : price, 'prod' : prod});

I recommend that you go back to the code where we declared those attributes. What were doing in the above code is just fetching the value in those attributes. If you’re updated with the latest web development news. You know that this is not how we ought to do things in the latest version of jquery. What we do is this:


Pretty much lighter on the fingers isn’t it? But I’m using a lower version of jquery when I was coding this so bear with me. You might as well download the latest version of jquery and reap all the benefits.

Okay so enough with that side dish. (I can’t think up of anything, bear with me). Then on the last second to the last line, we use a jquery load() function. Its basically used for loading up contents from another file in the server. The good thing is that we can also pass in arguments which will then be processed by the file that we specified.

So where is the result loaded? In the div that we created earlier. Scroll up if you’re uncertain.

So where is the session_creator.php file? Good question! I guess we will have to build it first before we continue with the rest of this tutorial.

The session_creator.php file, as the name implies is used to create a session where we will temporarily store the products added to the cart. We can pretty much achieve this using javascript cookies or maybe html 5 web storage. But I prefer to use php sessions.

First, assign all the post data to their corresponding variables. If you can remember the 3 variables below are the 3 variables that we passed earlier on the load() function.

$id = $_POST['prodid'];
$prod = $_POST['prod'];
$price = $_POST['price'];

Then we declared a variable called $add which we initialize to 0. We will use this variable to store the value of 1 or 0. 1 if the product that is being added already exist in the cart, 0 if its not. This is to avoid duplicate products on the cart.

$add = 0;

foreach($_SESSION['item_session'] as $k=>$v){
	if($v['prodid'] == $id){
		$add = 1;

if($add == 0){
	$_SESSION['item_session'][] = array('prodid'=>$id, 'prod'=>$prod, 'price'=>$price);

First thing that we did in the above code, is to determine if the item_session already exist. If it exists we loop through all of its data, and if it finds a product id which is similar to the one that is currently being added, then we set the $add variable to 1. Which means that the product was already added in the cart.
Then we only add the product to the cart if the $add variable has a value of 0. Which means that the product that’s currently being added does not still exist on the session array.

Next, we again check if the item_session array exist. If it exist, we build a table that contains all the products added to the cart.

<table border="1">
<?php foreach($_SESSION['item_session'] as $k=>$v){?> 
	<td><?php echo $v['prod']; ?></td>
	<td><?php echo $v['price']; ?></td>
	<td><input type="text" class="qty_class" name="qty[]" data-price="<?php echo $v['price']; ?>" data-qtyconn="<?php echo $k; ?>" readonly></td>
	<td><input type="text" class="sub_class" name="sub[]" data-subconn="<?php echo $k; ?>" readonly></td>
	<td><img src="del.png" class="del_class" id="<?php echo $k; ?>"></td>
<?php } ?>
<?php } ?>
Grand Total:
<input type="text" id="grand_total" name="grand_total" readonly>

This is similar to what we did when we fetched the product list from the database. The only difference is that this time were fetching it from a session array. And we also have a text box for inputting quantity to be bought, but its readonly by default to avoid the user from inputting anything before the selection is still not confirmed. This means that the user has to select the products first, confirm it, and then input the quantities for each product.  Though the user can still remove the products which were already added, he cannot add anything else once the selection has been confirmed.
Lastly we have the grand total textbox, which should be readonly for the rest of the program. Since it will display the total price for all the products added to cart.

Okay, so before we continue I need you to go back to the file that you were working with earlier. The one with the javascript code on it. Here’s the code for computing the subtotal, it only computes when the user tabs from the textbox with the qty_class. Scroll up and check to see if the data that were fetching from the quantity textbox really exist. Yes, we assigned data-price attribute in the textbox for inputting product quantity for the sole purpose of fetching it later on and multiply it with the quantity inputted by the user. As you can see from the code below, we did a little trick to determine which subtotal textbox we should put the result to. Scroll up again to the html code above. I’ll just share to you one of the tricks that I’m using. That is, if you need to connect 2 or more elements, then declare an attribute for each of those elements. Make the attribute name different, but make their values the same. This way, those 2 elements will have something common. And that is what were going to use to pinpoint the matching element. Lastly, we call up the total_looper() function. This function loops through all the textbox which contains the subtotal, it adds up all of those values to come up with the grand total.

$('.qty_class').live('blur', function(){
	var price = $(this).attr('data-price');
	var qty = Number($.trim($(this).val()));
	var qty_con = $(this).attr('data-qtyconn');
	var sub = qty *  price;
	$("input[data-subconn="+ qty_con +"]").val(sub);

Here’s the code for the total_looper() function. We always begin by setting the grand_total to 0. To make sure that we always start with 0 when looping through the contents of each sub total textbox. For looping I just used jquery’s each() function. In the code below, we used it to loop through all the elements with the class attribute of sub_class. If you scroll up to the html code, you will see that the subtotal text box has this class.

function total_looper(){
	var grand_total = 0;
		grand_total = Number($(this).val()) + grand_total;

Next, is the remove from cart button. This requires us to create another file called session_destroy.php. The only thing that we pass in that file is the product id. You’re always free to scroll up to see if the remove button indeed contains the product id. After that, we just remove the parent of the remove button. That is by using a neat jquery function called parents. Which requires a single argument which is the parent element.

$('.del_class').live('click', function(){
	var id = $(this).attr('id');
	$.post('session_destroy.php', {'id' : id});

Create a new php file. This is the file used for removing products which are already added in the cart. What we do is just loop through the item_session array. Then check if there is an item which has the same id with the one that the user tries to remove. Finally, we just use php’s unset() function to unset that particular item.

$id = $_POST['id'];

foreach($_SESSION['item_session'] as $k=>$v){
	if($k == $id){

And don’t forge the code for the confirm button. First, we issue a confirmation dialog to the user, and have the variable x store its value. The value is either true or false. If its true, then we hide the product list and set the quantity textbox readonly attribute to none. This allows the user to input quantity for each selected product.

	var x = confirm('Are you sure you dont want to buy anything else?');
	if(x == true){



Yes, you’ve reached the conclusion of this tutorial. In this tutorial, you learned how to create an ajax powered cart system. You’ve also learned some of the tricks that I don’t usually share to just anyone except for those who are reading my blog. As you can see, what I just showed you is a trimmed down version of a full-blown cart system. You might want to enhance the code that I used here and build your very own super-awesome cart system.
That’s all, see you next time!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: