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:SQL
- 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 ;
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.PHP
- 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");.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>
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.PHP
- 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>
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.JQUERY
- 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();
});
JQUERY
- 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
});
});
JQUERY
- 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
});
JQUERY
- 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.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
- 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 ) — $currency ".sprintf("%01.2f", ($product_price * $product_qty)). " <a href=\"#\" class=\"remove-item\" data-code=\"$product_code\">×</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.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
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 – $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";
}