Ajax Shopping Cart with PHP and jQuery

Shopping cart is an essential part of any E-commerce website that sells goods and services everyday over an internet, but the success rate of the online store is also determined by the convenience of whole buying process! Therefore, Ajax based Shopping Cart could be ideal platform, it can make things effortless for buyers.
Since my last tutorial about PHP Shopping Cart, I’ve received quite a few messages from users requesting an Ajax based Shopping cart tutorial! So today I am going to create the same by showing simple step by step examples, but I can’t guarantee it will be entirely novice friendly!

Create MySql Table

Before we start, we need to create a table in MySql database, which will store all the information regarding the products you want to sell, such as product name, id, description, price etc. For the tutorial, I have created a table called products_list:

1
2
3
4
5
6
7
8
CREATE TABLE IF NOT EXISTS 'products_list' (
'id' INT(11) NOT NULL,
  'product_name' VARCHAR(60) NOT NULL,
  'product_desc' text NOT NULL,
  'product_code' VARCHAR(60) NOT NULL,
  'product_image' VARCHAR(60) NOT NULL,
  'product_price' DECIMAL(10,2) NOT NULL
) AUTO_INCREMENT=1 ;

You can run the MySql code above manually in your PhpMyAdmin to create products_list table automatically. Or import products_list.sql (MySql file) in downloadable zip.
Here’s the list of products I have in my database table :
ajax-shopping-cart-sql-table

Configuration file

Let’s start by creating a config file called config.inc.php to store MySql credentials and other settings for later. We will be including this file where required to make MySql connection or to fetch currency or tax information.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$db_username        = 'root'; //MySql database username
$db_password        = ''; //MySql dataabse password
$db_name            = 'test'; //MySql database name
$db_host            = 'localhost'; //MySql hostname or IP

$currency           = '₹ '; //currency symbol
$shipping_cost      = 1.50; //shipping cost
$taxes              = array( //List your Taxes percent here.
                            'VAT' => 12,
                            'Service Tax' => 5,
                            'Other Tax' => 10
                            );

$mysqli_conn = new mysqli($db_host, $db_username, $db_password,$db_name); //connect to MySql
if ($mysqli_conn->connect_error) {//Output any connection error
    die('Error : ('. $mysqli_conn->connect_errno .') '. $mysqli_conn->connect_error);
}

Listing Products

Let’s create products page from MySql data. We can arrange these items as we like, we will include some CSS to make it look great. Since we will be accessing session variable, we need to include session_start(); on top of these files, followed by include(“config.inc.php”);.

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
<?php
session_start(); //start session
include("config.inc.php"); //include config file
?>
<!DOCTYPE HTML>
<html>
<head><title>Ajax Shopping Cart</title></head>
<body>
<?php
//List products from database
$results = $mysqli_conn->query("SELECT product_name, product_desc, product_code, product_image, product_price FROM products_list");
//Display fetched records as you please
$products_list =  '<ul class="products-wrp">';
while($row = $results->fetch_assoc()) {
$products_list .= <<<EOT
<li>
<form class="form-item">
<h4>{$row["product_name"]}</h4>
<div><img src="images/{$row["product_image"]}"></div>
<div>Price : {$currency} {$row["product_price"]}<div>
<div class="item-box">
    <div>
    Color :
    <select name="product_color">
    <option value="Red">Red</option>
    <option value="Blue">Blue</option>
    <option value="Orange">Orange</option>
    </select>
    </div><div>
    Qty :
    <select name="product_qty">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    </select>
    </div><div>
    Size :
    <select name="product_size">
    <option value="M">M</option>
    <option value="XL">XL</option>
    <option value="XXL">XLL</option>
    </select>
    </div>
   
    <input name="product_code" type="hidden" value="{$row["product_code"]}">
    <button type="submit">Add to Cart</button>
</div>
</form>
</li>
EOT
;

}
$products_list .= '</ul></div>';
echo $products_list;
?>
</body>
</html>

After all the arrangement and styling, our products page should look something like picture below. We will use jQuery to capture values from these items, which we will use to update the shopping cart.
ajax-shopping-cart-products-list

Adding Shopping Cart Box

Once we have created the products page, we can now add a cart box somewhere within the page. This cart-box gets automatically updated when user adds/removes the items from products list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<a href="#" class="cart-box" id="cart-info" title="View Cart">
<?php
if(isset($_SESSION["products"])){
    echo count($_SESSION["products"]);
}else{
    echo 0;
}
?>
</a>
<div class="shopping-cart-box">
<a href="#" class="close-shopping-cart-box" >Close</a>
<h3>Your Shopping Cart</h3>
    <div id="shopping-cart-results">
    </div>
</div>

Using CSS I’ve changed the look of this cart box in picture below.
ajax-shopping-cart-box

Implementing Ajax with jQuery

In order to update the shopping cart with items without reloading the page, we need to send data to server using HTTP (Ajax) request. Since most of us are using jQuery JavaScript library on our websites, we will implement it using jQuery’s Ajax Method. The following code will make Ajax request to server and update our shopping cart.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//Add Item to Cart
$(".form-item").submit(function(e){ //user clicks form submit button
    var form_data = $(this).serialize(); //prepare form data for Ajax post
    var button_content = $(this).find('button[type=submit]'); //get clicked button info
    button_content.html('Adding...'); //Loading button text //change button text

    $.ajax({ //make ajax request to cart_process.php
        url: "cart_process.php",
        type: "POST",
        dataType:"json", //expect json value from server
        data: form_data
    }).done(function(data){ //on Ajax success
        $("#cart-info").html(data.items); //total items count fetch in cart-info element
        button_content.html('Add to Cart'); //reset button text to original text
        alert("Item added to Cart!"); //alert user
        if($(".shopping-cart-box").css("display") == "block"){ //if cart box is still visible
            $(".cart-box").trigger( "click" ); //trigger click to update the cart box.
        }
    })
    e.preventDefault();
});

To remove an item from cart, we need to trigger the following jQuery code, as you can see I have used $.getJSON() method, as we will be expecting JSON data from server:

1
2
3
4
5
6
7
8
9
10
//Remove items from cart
$("#shopping-cart-results").on('click', 'a.remove-item', function(e) {
    e.preventDefault();
    var pcode = $(this).attr("data-code"); //get product code
    $(this).parent().fadeOut(); //remove item element from box
    $.getJSON( "cart_process.php", {"remove_code":pcode} , function(data){ //get Item count from Server
        $("#cart-info").html(data.items); //update Item count in cart-info
        $(".cart-box").trigger( "click" ); //trigger click on cart-box to update the items list
    });
});

If user wants to view his cart, we simply display the cart box using code below.

1
2
3
4
5
6
7
//Show Items in Cart
$( ".cart-box").click(function(e) { //when user clicks on cart box
    e.preventDefault();
    $(".shopping-cart-box").fadeIn(); //display cart box
    $("#shopping-cart-results").html('<img src="images/ajax-loader.gif">'); //show loading image
    $("#shopping-cart-results" ).load( "cart_process.php", {"load_cart":"1"}); //Make ajax request using jQuery Load() & update results
});

The jQuery code below simply closes the cart-box when user clicks the close button.

1
2
3
4
5
//Close Cart
$( ".close-shopping-cart-box").click(function(e){ //user click on cart box close link
    e.preventDefault();
    $(".shopping-cart-box").fadeOut(); //close cart-box
});

PHP Cart Processing

Our product page is ready to update the cart, but there’s no background script to process the data sent via Ajax. For that we need to create a server side PHP script, which will obliquely process and send relevant data back to the client’s page. Let’s create a PHP file called cart_process.php.

If you have read Updating Cart in my previous post Creating Simple Shopping Cart with PHP, you will notice the code similarities here. We will be applying the similar technique using PHP session variable to create multidimensional array, which holds the item values, and can be manipulated as per the needs.

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
session_start(); //start session
include_once("config.inc.php"); //include config file
setlocale(LC_MONETARY,"en_US"); // US national format (see : http://php.net/money_format)
############# add products to session #########################
if(isset($_POST["product_code"]))
{
    foreach($_POST as $key => $value){
        $new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING); //create a new product array
    }
   
    //we need to get product name and price from database.
    $statement = $mysqli_conn->prepare("SELECT product_name, product_price FROM products_list WHERE product_code=? LIMIT 1");
    $statement->bind_param('s', $new_product['product_code']);
    $statement->execute();
    $statement->bind_result($product_name, $product_price);
   

    while($statement->fetch()){
        $new_product["product_name"] = $product_name; //fetch product name from database
        $new_product["product_price"] = $product_price;  //fetch product price from database
       
        if(isset($_SESSION["products"])){  //if session var already exist
            if(isset($_SESSION["products"][$new_product['product_code']])) //check item exist in products array
            {
                unset($_SESSION["products"][$new_product['product_code']]); //unset old item
            }          
        }
       
        $_SESSION["products"][$new_product['product_code']] = $new_product; //update products with new item array  
    }
   
    $total_items = count($_SESSION["products"]); //count total items
    die(json_encode(array('items'=>$total_items))); //output json

}

################## list products in cart ###################
if(isset($_POST["load_cart"]) && $_POST["load_cart"]==1)
{

    if(isset($_SESSION["products"]) && count($_SESSION["products"])>0){ //if we have session variable
        $cart_box = '<ul class="cart-products-loaded">';
        $total = 0;
        foreach($_SESSION["products"] as $product){ //loop though items and prepare html content
           
            //set variables to use them in HTML content below
            $product_name = $product["product_name"];
            $product_price = $product["product_price"];
            $product_code = $product["product_code"];
            $product_qty = $product["product_qty"];
            $product_color = $product["product_color"];
            $product_size = $product["product_size"];
           
            $cart_box .=  "<li> $product_name (Qty : $product_qty | $product_color  | $product_size ) &mdash; $currency ".sprintf("%01.2f", ($product_price * $product_qty)). " <a href="#" class="remove-item" data-code="$product_code">&times;</a></li>";
            $subtotal = ($product_price * $product_qty);
            $total = ($total + $subtotal);
        }
        $cart_box .= "</ul>";
        $cart_box .= '<div class="cart-products-total">Total : '.$currency.sprintf("%01.2f",$total).' <u><a href="view_cart.php" title="Review Cart and Check-Out">Check-out</a></u></div>';
        die($cart_box); //exit and output content
    }else{
        die("Your Cart is empty"); //we have empty cart
    }
}

################# remove item from shopping cart ################
if(isset($_GET["remove_code"]) && isset($_SESSION["products"]))
{
    $product_code   = filter_var($_GET["remove_code"], FILTER_SANITIZE_STRING); //get the product code to remove

    if(isset($_SESSION["products"][$product_code]))
    {
        unset($_SESSION["products"][$product_code]);
    }
   
    $total_items = count($_SESSION["products"]);
    die(json_encode(array('items'=>$total_items)));
}

Cart Summery view

Finally we will create a summery view page to show total costs including taxes, this is the page where users know exactly what they will have to pay when they decide to purchase.

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
if(isset($_SESSION["products"]) && count($_SESSION["products"])>0){
    $total          = 0;
    $list_tax       = '';
    $cart_box       = '<ul class="view-cart">';

    foreach($_SESSION["products"] as $product){ //Print each item, quantity and price.
        $product_name = $product["product_name"];
        $product_qty = $product["product_qty"];
        $product_price = $product["product_price"];
        $product_code = $product["product_code"];
        $product_color = $product["product_color"];
        $product_size = $product["product_size"];
       
        $item_price     = sprintf("%01.2f",($product_price * $product_qty));  // price x qty = total item price
       
        $cart_box       .=  "<li> $product_code &ndash;  $product_name (Qty : $product_qty | $product_color | $product_size) <span> $currency. $item_price </span></li>";
       
        $subtotal       = ($product_price * $product_qty); //Multiply item quantity * price
        $total          = ($total + $subtotal); //Add up to total price
    }
   
    $grand_total = $total + $shipping_cost; //grand total
   
    foreach($taxes as $key => $value){ //list and calculate all taxes in array
            $tax_amount     = round($total * ($value / 100));
            $tax_item[$key] = $tax_amount;
            $grand_total    = $grand_total + $tax_amount;
    }
   
    foreach($tax_item as $key => $value){ //taxes List
        $list_tax .= $key. ' '. $currency. sprintf("%01.2f", $value).'<br />';
    }
   
    $shipping_cost = ($shipping_cost)?'Shipping Cost : '.$currency. sprintf("%01.2f", $shipping_cost).'<br />':'';
   
    //Print Shipping, VAT and Total
    $cart_box .= "<li class="view-cart-total">$shipping_cost  $list_tax <hr>Payable Amount : $currency ".sprintf("%01.2f", $grand_total)."</li>";
    $cart_box .= "</ul>";
   
    echo $cart_box;
}else{
    echo "Your Cart is empty";
}

That’s it! all you now need to do is pass these values to your Payment Gateway when user clicks pay button. You can generate any type of data here for the Payment gateway, most Payment gateway prefer HTML form, so you can create hidden input fields with values and post them to your Payment Gateway website.

Download Demo

54 Comments Add Comment

  • Just one problem man. the facilitator was not able to receive the money from the client. Am I the only one with this? is there anybody here who have already fixed this? thanks in a advance

     Reply
  • Thanks for the tutorial, really amazing!
    I would to ask you if possible to include, and how to, a SEARCH field above the list of products, for to show only the products with description similar to the one searched. If the field is empty, the product list complete.

     Reply
  • If I wanted to add Name and Address as I could do?

     Reply
  • Just needed about 5 lines from your entire script and really helped in my work. Thanks

     Reply
  • Hello, Saran!

    I see that if I add a product to cart and want to add the same product again, the quantity does not increase. Also, if I want to add the same product in different size, the previous product gets deleted.

    Another thing is, how can I have different prices for different sizes?

    Thanks!

     Reply
  • Halo bro,

    a can qestion, how tutorial if a can INSERT to database after viewCart from your tutorial ? thank before bro, i very very you hope i.thank

     Reply
  • How about with a table quantity? How can I update my quantity table after purchasing a specific item. Please Help me

     Reply
  • HI,
    Thank for you script, are the dowloadable sources supposed to work with PHP 7 ?
    Kr
    Olivier

     Reply
  • How do i get the items selected so i can now what they ordered i made my own checkout.php

     Reply
  • Hello Saran, i keep getting this error in trying to test on index page

    Fatal error: Call to a member function fetch_assoc() on a non-object

    tried some solutions online from stacksoverflow but i cant seem to solve it

     Reply
  • This great tutorial. Thanks

     Reply
  • Great Tutorial
    How to do if you buy multiple items from same references with different colors and sizes
    the script keeps only the latest product code ?

    Thank you

     Reply
  • Hi Saran
    is it maybe possible that you can update a item in your shopping cart with a input text and update button?

     Reply
  • Hello, anyone know how to update quantity after add to cart? either update at the cart list or view cart page

     Reply
  • good tutorial and good script, thank you.
    There is only one thing i don’t get about the script. When you add a t-shirt with size m, and the same product with size s, the product does not show in de cart. Is there a solution for this?

     Reply
  • hi..i run you codes…working perfectly. But i tried to embed your code into my website…when i click on add to cart button the cart shows “1” when i click on another item still showing ‘1’ as only one item is added to the cart but when i try to view if ts real added, The cart reads empty..Please help!
    Thanks.

     Reply
  • i am beginner in php one training start kindly provide some notes for my bright future

     Reply
  • I would be interested in hiring you to integrate this cart on my site (already have catalog) as well as adding payment script to it. Let me know if you are interested and we can go from there.

    Gary

     Reply
  • Hello,
    how I can handle the addition of the same model in two sizes, XL and XXL for example.
    Thank you

     Reply
  • i have imported the sql file in xamp
    but i am gettin this error:
    Fatal error: Call to a member function fetch_assoc() on a non-object in C:\xampp\htdocs\index.php on line 92

     Reply
  • Hi,
    I want to Display the Quantity of product added to cart instead of number of products in cart. Suppose if i select 2 for the Quantity then in Cart it should display the 2 rather than 1.
    what if i want to use the “+” & “-” icon to increase & decrease the Quantity instead of select box.
    Please help me out its urgent

     Reply
  • I’ve yet to go through this entire tutorial, but I’m a little confused; how can we check for the session variable:

    1
    $_SESSION["products"]

    when we’ve never set the variable?

     Reply
    • if(isset($_POST[“product_code”]))
      {
      foreach($_POST as $key => $value){
      $new_product[$key] = $value; //create a new product array
      }

      this is where the magic begin…

  • Awesome tutorial.
    Question: How can you add a radio button?

     Reply
  • Great Tutorial
    Thanks ….

     Reply
  • Why use this code and what is the purpose of this

    $products_list = ”;

    $products_list .= <<<EOT

    .
    .
    EOT;

    }
    $products_list .= '’;
    echo $products_list;

     Reply
  • Hello Saran,

    Thanks for your tutorial, it’s really amazing.
    Well, I’m having a little problem because I’m trying to create fashion website. so you know when we click on any product from product page then normally next product detail page come where we can see all detail of that product which we choose, but when i click on any product from product page then next detail page come and it’s show all product ID detail from db in same page. so i just want to show detail of the product which we choose and then add to cart there etc. here is code please help me and Thanks in advance.
    For example:
    query(“SELECT * FROM short_sleeves_shirt WHERE status=’Yes’ ORDER BY name ASC”);
    if ($results) {

    //fetch results set as object and output HTML
    while($obj = $results->fetch_object())
    {
    echo ”.$obj->name.’ ‘;
    echo ”.$obj->code.’ ‘;
    echo ”.$obj->price.’ ‘;
    }
    }
    ?>

     Reply
  • Awesome tutorial, thank you so much. Really helped me out.

     Reply
  • Please add ‘update quantity’ after adding to cart using jquery.

     Reply
  • Please add update quantity functionality after add to cart. please… please…..

     Reply
  • As first, thanks very much. I have one question. When i click temove in my cart, the item is deleted, but Total fee to be paid stays the same. How to fix it, please…

     Reply
  • Hey Saran,
    I am using above code and have customized it according to requirements. I have a one product having multiple colors. when i added that in shopping cart and removed one of them then cart becomes empty. To remove product i need to check product color along with product code(data-code in above case). I have changed $.getJSON() method(from index.php), list products in cart,remove item from shopping cart from the cart_process.php. But remove item from cart is not working properly. Can you tell me please, how should I work with multiple parameters in this scenario?

     Reply
    • Hi i have just updated the tutorial, please checkout demo and download new files.

    • Hey Saran,
      Thanks a lot. that is what I was looking for. But now the problem is in demo, one product with different color is not added. Its just updating the same product with different color or size. e.g. if I want to add ‘Cool T-shirt | Red | M’ and ‘Cool T-shirt | Blue | XLL’ . These two products are different. But its just updating ‘Cool T-shirt | Red | M’ with color and size. So there is only one product in cart instead of two. And according removal should also happen. How this is possible? Please tell me this also. Thanks a lot.

    • Hey Saran,
      Can you please tell me how the ‘product_color’ should be add to your ‘add products to session’ and ‘remove item from shopping cart’ sections mentioned in your PHP Cart Processing code?
      I am unable to this to achieve this – If users adds any item, and then wants to add that same item but with different requirements, should be added as a separate entry int the cart session.(only if the specific variable gets changed, for example: A single product but with different colors/sizes).
      Please please tell and explain this how this can be done? Thanks Saran.

    • Hey Saran,
      Please suggest something or help in above scenarios. Your tutorial is really good one and easy to understand. But I didn’t get the solution still. Can you please help me in this?
      Waiting for reply.
      Thanks Saran.

    • This happens because it populate the cart and session based on “product_code”, so If you add a item with product_code= ‘1’ with no OPTIONS and later add the same product again with differents option at will replace the last one, since it’s the same code. What you need to do it’s to create a ITEM ID.
      ex: CART
      1 – Product “1” NO OPTIONS
      2 – Product “1” WITH OPTIONS
      ——————————————–
      What I did? Inside the I just added another HIDDEN INPUT named “codigoitem”.(whatever you want).

      1
      2
      <input type="hidden" name="codigoitem" id="codigo" class="resultado"  value="">
      <input  type="hidden" name="product_code" value="'.$l_grupo['product_code'].'">

      This input is populated with the CART ITEM COUNT VALUE + 1.
      I did with a jquery function.

      1
      2
      3
                      var coditem = $('#cart-info').text();
                      coditem++;
                      $('.resultado').val(coditem);

      and changed the cart_process.php

      1
      2
      3
          //we need to get product name and price from database.
          $statement = $mysqli_conn->prepare("SELECT product_name, product_price, product_image FROM products_list WHERE product_code=? ");
          $statement->bind_param('s', $new_product['codigoitem']);

      So when I gonna add a item it get the current cart count and add + 1.
      Ex: CART – 0
      Product ONE – code = 1 – codigoitem = 1

      If I add the same product:
      Product ONE – code = 1 – codigoitem = 2
      ………………………………………………
      That’s the way I did !

    • This post helped me alot. This code is just like a “TO WORK” code… I will improve it later, but for now it’s doing what I want.
      The jquery function should be added to ADD CART PRODUCT and REMOVE CART PRODUCT function, as well when u load page with $(document).ready

    • Hey Alexandre,
      Thanks for the reply. I have tried the code that you mentioned on the Saran’s updated tutorial code. But the items not getting added to cart. I have added HIDDEN input, cart_process.php code, also I have added your jquery function to “$(document).ready(function(){ “, “$(“.form-item”).submit(function(e){” and “$(“#shopping-cart-results”).on(‘click’, ‘a.remove-item’, function(e) {“. Can you please tell me what I am missing? Is anything other than this needs to be changed?
      Waiting for reply.
      Thanks .

  • Thanks for your information.

     Reply
  • i need help regarding online shopping cart in php ..regarding my project

     Reply
  • thanks your tips

     Reply
  • Its amazing This is what exactly im looking for really nice work thanks a lot.

     Reply
  • Hello
    Please I do not see the where the description that you entered in the database is

     Reply
  • Hi saran,

    Hello
    URL tutorial(‘http://www.sanwebe.com/2012/07/paypal-expresscheckout-with-php/comment-page-3#comment-12755’)
    i used sandbox api for testing and its working fine but when i used the Api credential i got error,
    can you help me to fix this error.. thanks in advance..
    Error : Security header is not valid

    Array
    (
    [TIMESTAMP] => 2015%2d04%2d21T02%3a22%3a10Z
    [CORRELATIONID] => ead7986d9a2
    [ACK] => Failure
    [VERSION] => 109%2e0
    [BUILD] => 16309297
    [L_ERRORCODE0] => 10002
    [L_SHORTMESSAGE0] => Security%20error
    [L_LONGMESSAGE0] => Security%20header%20is%20not%20valid
    [L_SEVERITYCODE0] => Error
    )

     Reply
  • Sernian Mckinsley

    Thanks Saran, i’ll use this php chart function on my motorcycle ecommerce website.

     Reply
  • Great Turtorial. Thanks

     Reply
  • I can’t delete/remove the products. If anyone willing to help, please reply. Thanks.

     Reply
    • You have to edit the page in the ajax request that enables you to delete the file.