Ajax Shopping Cart with PHP and jQuery
Create MySql Table
--
-- Table structure for table `products_list`
--
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
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--
-- Dumping data for table `products_list`
--
INSERT INTO `products_list` (`id`, `product_name`, `product_desc`, `product_code`, `product_image`, `product_price`) VALUES
(1, 'Cool T-shirt', 'Cool T-shirt, Cotton Fabric. Wash in normal water with mild detergent.', 'TSH1', 'tshirt-1.jpg', '8.50'),
(2, 'HBD T-Shirt', 'Cool Happy Birthday printed T-shirt.Crafted from light, breathable cotton.', 'TSH2', 'tshirt-2.jpg', '7.40'),
(3, 'Survival of Fittest', 'Yellow t-shirt makes the perfect addition to your casual wardrobe.', 'TSH3', 'tshirt-3.jpg', '9.50'),
(4, 'Love Hate T-shirt', 'Stylish and trendy, this crew neck short sleeved t-shirt is made with 100% pure cotton.', 'TSH4', 'tshirt-4.jpg', '10.80');
Configuration file
<?php
$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
<?php
session_start(); //start session
include("config.inc.php"); //include config file
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Ajax Shopping Cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){
$(".form-item").submit(function(e){
var form_data = $(this).serialize();
var button_content = $(this).find('button[type=submit]');
button_content.html('Adding...'); //Loading 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 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();
});
//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
});
//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
});
//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
});
});
});
</script>
</head>
<body>
<div align="center">
<h3>Ajax Shopping Cart Example</h3>
</div>
<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>
<?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>
Add Cart process
<?php
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)));
}
Add View Cart
<?php
session_start(); //start session
include("config.inc.php");
setlocale(LC_MONETARY,"en_US"); // US national format (see : http://php.net/money_format)
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Review Your Cart Before Buying</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h3 style="text-align:center">Review Your Cart Before Buying</h3>
<?php
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";
}
?>
</body>
</html>
Add CSS style
body {
background-color: #F9F9F9;
font-family: Georgia, "Times New Roman", Times, serif;
}
ul.products-wrp {
list-style: none;
padding: 0;
max-width: 650px;
margin-left: auto;
margin-right: auto;
color: #777;
text-align: center;
}
ul.products-wrp li{
display: inline-block;
border: 1px solid #ECECEC;
margin: 5px;
background: #fff;
text-align: center;
}
ul.products-wrp li h4{
margin: 0;
padding: 15px 5px 5px 5px;
text-align: center;
border-bottom: 1px solid #FAFAFA;
}
ul.products-wrp li .item-box{
border: 1px solid #EAEAEA;
background: #F9F9F9;
margin: 5px;
padding: 5px;
text-align: left;
}
ul.products-wrp li .item-box div{
margin-bottom:5px;
}
ul.products-wrp li .item-box button{
margin-left: 5px;
background: #FA1C5F;
border: none;
padding: 3px 8px 3px 8px;
color: #fff;
}
ul.products-wrp li .item-box button[disabled=disabled]{
background: #FC84A8;
}
.cart-box {
display: block;
width: 30px;
background: rgba(219, 0, 33, 1) url(../images/cart-icon.png) no-repeat 20px 5px;
padding: 4px 8px 4px 8px;
border-radius: 30px;
color: #fff;
font-family: Arial;
font-size: 16px;
text-decoration: none;
box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.32);
margin-right: auto;
margin-left: auto;
font-weight: bold;
}
.cart-box:hover{
background: #FA1C5F url(../images/cart-icon.png) no-repeat 20px 5px;
}
.shopping-cart-box{
position: absolute;
left:0;
right:0;
margin-left:auto;
margin-right:auto;
max-width: 450px;
color: #FFD5D5;
background: #FA1C5F;
border-radius: 4px;
padding: 10px;
font: small Verdana, Geneva, sans-serif;
margin-top: 10px;
display:none;
}
.shopping-cart-box a{
color: #FFD5D5;
text-decoration:none;
}
.shopping-cart-box:after {
content: '';
position: absolute;
bottom: 100%;
left: 50%;
margin-left: -8px;
width: 0; height: 0;
border-bottom: 8px solid rgba(255, 0, 97, 1);
border-right: 8px solid transparent;
border-left: 8px solid transparent;
}
.shopping-cart-box ul.cart-products-loaded{
margin: 0;
padding: 0;
list-style: none;
}
.shopping-cart-box .close-shopping-cart-box{
float: right;
}
#shopping-cart-results ul.cart-products-loaded li{
background: #ED0C50;
margin-bottom: 1px;
padding: 6px 4px 6px 10px;
}
.shopping-cart-box .remove-item{
float:right;
text-decoration:none;
}
.shopping-cart-box .cart-products-total{
font-weight: bold;
text-align: right;
padding: 5px 0px 0px 5px;
}
.shopping-cart-box h3{
margin: 0;
padding: 0px 0px 5px 0px;
}
ul.view-cart {
width: 600px;
margin-left: auto;
margin-right: auto;
background: #fff;
padding: 15px 15px 15px 25px;
list-style: none;
}
ul.view-cart {
width: 600px;
margin-left: auto;
margin-right: auto;
background: #fff;
padding: 15px 15px 15px 25px;
list-style: none;
border: 1px solid #ECECEC;
border-radius: 4px;
}
ul.view-cart li span{
float: right;
}
ul.view-cart li.view-cart-total{
border-top: 1px solid #ddd;
padding-top: 5px;
margin-top: 5px;
text-align: right;
}
hr{
border: 0;
height: 0;
border-top: 1px solid rgba(0, 0, 0, 0.1);
border-bottom: 1px solid rgba(255, 255, 255, 0.3);
}