32,000+ SUBSCRIBERS CAN'T GO WRONG !!!

phpans
GET TOP ARTICLES, SNIPPETS, SCRIPTS IN YOUR INBOX FOR FREE!

Delivered by GET EMAIL UPDATES FeedBurner
We always respect your privacy and take protecting it seriously.
We won't Spam You

AJAX PHP Shopping Cart with jQuery

, 1,
AJAX PHP Shopping Cart with jQuery
In this tutorial, we are going to create AJAX PHP Shopping Cart with jQuery and PHP Shopping Cart with jQuery AJAX is our todays project. Before, We have created Ajax Login Form and Ajax PHP Newsletter project using jQuery and PHP. Our todays taks is PHP Shopping Cart. Before starting step by step tutorial see working PHP Shopping Cart Demo here. Then download the attached file or demo file and start reading and creating.

Create MySQL Database


Create a database and execute SQL code which is provided in products.sql file in the source code. When you execute this SQL It will be added some products automatically.
products.sql
CREATE TABLE IF NOT EXISTS `products` (
`id` int(8) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`code` varchar(255) NOT NULL,
`image` text NOT NULL,
`price` double(10,2) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `product_code` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;


INSERT INTO `products` (`id`, `name`, `code`, `image`, `price`) VALUES
(1, 'Hugo Boss', 'HugoBoss01', 'product-images/hugo-boss.jpg', 950.00),
(2, 'Fastrack', 'FasTrack02', 'product-images/fastrack.jpg', 1145.00),
(3, 'Luminox', 'Luminox03', 'product-images/luminox.jpg', 1200.00),
(4, 'Emporio Armani', 'EmporioArmani04', 'product-images/emporio-armani.jpg', 1090.00),
(5, 'Diesel', 'Diesel05', 'product-images/diesel.jpg', 6609.00),
(6, 'Armani Swiss', 'ArmaniSwiss06', 'product-images/armani-swiss.jpg', 10981.00),
(7, 'Michael Kors', 'MichaelKors07', 'product-images/michael_kors.jpg', 745.00);


AJAX PHP Shopping Cart with jQuery MySQL Table


Create Stylesheet



Now we are going to create a stylesheet for this project. Create a directory name as asset and create a stylesheet name as styles.css into asset directory.
styles.css
header{padding: 10px;font-weight:bold;font-size:25px}
.peoduct-header{padding:5px;font-weight:bold;font-size:20px}
.cart{font-size:30px;}
.quantity{width:50px;border-radius:5px;padding:5px;}
.add{color:#008040;cursor:pointer;}
.added{color:#A4A6A9;cursor:pointer;}
.cart-items {background:#F0F0F0;max-height:300px;overflow:auto;}
.mycart {border-bottom: #79b946 1px dotted;}
.product-price {color:#5E8608;font-weight:bold}
.product-image {height:100px;background-color:#FFF;}
.product-image img {height:100px;width:100px;}
.cart-action{cursor:pointer;}
.remove{font-size:30px;color:#F80B37}
#notification{display:none;top:10;left:10;right:0;bottom:0;position:fixed;z-index:200}
.empty{cursor:pointer;}
footer{padding: 10px;font-weight:bold;font-size:15px}

These styles will be use on out shopping cart project.
After completing this step you should configure your MySQL credentials in db.class.php

Configer Database


For configuring database, you should update db.class.php file with appropriate database informations. db.class.php database configuaration file. Here is all database operations.
db.class.php
<?php
class DBactions {

public function __construct() {
$conn= mysqli_connect('localhost','db_user','db_pasword','db_name');
if(!$conn){@die('MySQL error!');}else{$this->conn = $conn;}
}
public function runQuery($Query)
{
$result = mysqli_query($this->conn,$Query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
public function runAssoc($Query)
{
$query = mysqli_query($this->conn,$Query) or die(mysqli_error($this->conn));
$Assoc = mysqli_fetch_assoc($query);
return $Assoc;
}


}
?>

Change and edit database information and config it database name, database username, database password and set up your own.

Create Product List File


Create index.php file for display products from the database. Products will be displayed from products table. create index file and write this code bellow.
index.php
<?php
@session_start();
require_once("db.class.php");
$db_handle = new DBactions();
echo '<!DOCTYPE html>';
echo '<html lang="en">';
echo '<head>';
echo '<meta charset="utf-8">';
echo '<meta http-equiv="X-UA-Compatible" content="IE=edge">';
echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
echo '<title>AJAX PHP Shopping Cart with jQuery</title>';
echo '<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">';
echo '<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">';
echo '<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>';
echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>';
echo '<link href="asset/styles.css" type="text/css" rel="stylesheet" />';
echo '<script src="asset/scripts.js" type="text/javascript"></script>';
echo '</head>';
echo '<body>';
echo '<div class="container">';
echo '<header class="bg-primary text-center">AJAX PHP Shopping Cart with jQuery</header>';
echo '<div class="row">';

echo '<div class="col-lg-8 col-md-8 col-sm-12">';
echo '<div class="bg-success text-center peoduct-header">Products</div>';
$product_array = $db_handle->runQuery("SELECT * FROM products ORDER BY id ASC");
if (!empty($product_array)) {
echo '<div class="row">';
foreach($product_array as $key=>$value){
echo '<div class="col-lg-4 col-md-4 col-sm-12 text-center">';
echo '<div class="product-image"><img src="'.$product_array[$key]["image"].'"></div>';
echo '<div class="product-name">'.$product_array[$key]["name"].'</div>';
echo '<div class="product-price">$'.$product_array[$key]["price"].'</div>';
echo '<div><input type="number" class="quantity '.$product_array[$key]["code"].'" name="quantity" value="1" size="2"></div>';
$in_session = "0";
if(!empty($_SESSION["products"])) {
$session_code_array = array_keys($_SESSION["products"]);
if(in_array($product_array[$key]["code"],$session_code_array)) {
$in_session = "1";
}
}
if($in_session == "0"){$style="add";}else{$style="added";}

echo '<span id="'.$product_array[$key]["code"].'" class="cart add"><i class="fa fa-cart-plus"></i></span>';
echo ' <span id="'.$product_array[$key]["code"].'" class="remove added"><i class="fa fa-minus-circle"></i></span>';
echo'</div>';

}
echo '</div>';
}

echo '</div>';
echo '<div class="col-lg-4 col-md-4 col-sm-12">';
echo '<div class="bg-success text-center peoduct-header">';
echo '<i class="fa fa-cart-arrow-down"></i> Your Shopping Cart <span class="badge empty"><i class="fa fa-trash-o"></i> Empty</span></div>';
echo '<div id="mycart" class="cart-items"></div>';
echo '</div>';
echo '</div>';
echo '<span id="notification"></span>';
echo '<footer class="bg-primary text-center">&copy; phpans.com</footer>';
echo '</div>';
echo '</body>';
echo '</html>';
?>

AJAX PHP Shopping Cart Product List

User added products will be displayed in right Your Shopping Cart section. Users could add every product in their shopping cart using icon and delete products using icon.

jQuery Functions


Now we are going to process ajax request. we need jQuery library we already added jQuery library and scripts.js file in index.php file.
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="asset/scripts.js" type="text/javascript"></script>

we have added asset/script.js so create a script.js file into asset directory and write down this code bellow into this file. this code will sent ajax requests.
scripts.js
$(document).ready(function (){
$("#mycart").load("actions.php");

$(".cart").click(function (){
var product = $(this).attr('id');
var quantity = $('.'+ product).val();
var t = "action=add&code="+ product + "&quantity=" + quantity;
if(quantity > 0)
{
$.ajax({
type: "POST",
url: "actions.php",
data: t,
cache: !1,
beforeSend: function() {
$("#"+ product +" .fa-cart-plus").removeClass('fa-cart-plus').addClass('fa-spinner').addClass('fa-pulse').addClass('fa-fw')
},
success: function(e) {
$("#"+ product +" .fa-spinner").addClass('fa-cart-plus').removeClass('fa-spinner').removeClass('fa-pulse').removeClass('fa-fw'),
$("#notification").fadeIn().delay(5e2).fadeOut().html('<span class="glyphicon glyphicon-ok-circle"></span> Item Added').removeClass('alert alert-warning').addClass('alert alert-success'),$("#mycart").html(e)
}
});
}
else {$("#notification").fadeIn().delay(2e3).fadeOut().html('<span class="glyphicon glyphicon-remove-circle"></span> Please add minimum 1 product').addClass('alert alert-warning')}
});

$(".empty").click(function (){
var t = "action=empty";
$.ajax({
type: "POST",
url: "actions.php",
data: t,
cache: !1,
beforeSend: function() {
$("#empty").html('wait...')
},
success: function(e) {
$("#notification").fadeIn().delay(5e2).fadeOut().html('<span class="glyphicon glyphicon-ok-circle"></span> All items removed').removeClass('alert alert-warning').addClass('alert alert-success'),$("#mycart").html(e)

}
});
});
$(".remove").click(function (){
var product = $(this).attr('id');
var t = "action=remove&code="+ product;
if($.trim(product).length > 0)
{
$.ajax({
type: "POST",
url: "actions.php",
data: t,
cache: !1,
beforeSend: function() {
$("#"+ product +" .fa-minus-circle").removeClass('fa-minus-circle').addClass('fa-spinner').addClass('fa-pulse').addClass('fa-fw')
},
success: function(e) {
$("#"+ product +" .fa-spinner").addClass('fa-minus-circle').removeClass('fa-spinner').removeClass('fa-pulse').removeClass('fa-fw'),
$("#notification").fadeIn().delay(5e2).fadeOut().html('<span class="glyphicon glyphicon-ok-circle"></span> Item Removed').removeClass('alert alert-warning').addClass('alert alert-success'),$("#mycart").html(e)
}
});
}
else {$("#notification").fadeIn().delay(2e3).fadeOut().html('<span class="glyphicon glyphicon-remove-circle"></span> Please add minimum 1 product').addClass('alert alert-warning')}
});

});

All necessary jQuery functions added into this file. product add, product remove and others. Now we are on the way to create ajax processing file. All of our requirements has added.

Cart Process Option


We have added our required javascript and styles now cart process option is ready. we have used action.php in script.js file and now create action.php file and write down this code bellow.
action.php
<?php
@session_start();
require_once("db.class.php");
$db_handle = new DBactions();

if(!empty($_POST["action"])) {
switch($_POST["action"]) {
case "add":
if(!empty($_POST["quantity"])) {
$productInfo = $db_handle->runQuery("SELECT * FROM products WHERE code='" . $_POST["code"] . "'");
$itemArray = array($productInfo[0]["code"]=>array('name'=>$productInfo[0]["name"], 'code'=>$productInfo[0]["code"], 'quantity'=>$_POST["quantity"], 'price'=>$productInfo[0]["price"]));

if(!empty($_SESSION["products"])) {
if(in_array($productInfo[0]["code"],$_SESSION["products"])) {
foreach($_SESSION["products"] as $k => $v) {
if($productInfo[0]["code"] == $k)
$_SESSION["products"][$k]["quantity"] = $_POST["quantity"];
}
} else {
$_SESSION["products"] = array_merge($_SESSION["products"],$itemArray);
}
} else {
$_SESSION["products"] = $itemArray;
}
}
break;
case "remove":
if(!empty($_SESSION["products"])) {
foreach($_SESSION["products"] as $k => $v) {
if($_POST["code"] == $k)
unset($_SESSION["products"][$k]);
if(empty($_SESSION["products"]))
unset($_SESSION["products"]);
}
}
break;
case "empty":
unset($_SESSION["products"]);
break;
}
}

if(isset($_SESSION["products"])){
$item_total = 0;
$quantity_total = 0;
echo '<table class="table table-striped">';
echo '<thead>';
echo '<tr>';
echo '<th>Name</th>';
echo '<th>Quantity</th>';
echo '<th>Price</th>';
echo '</tr>';
echo '</thead>';
foreach ($_SESSION["products"] as $item){
echo '<tr>';
echo '<td><strong>'.$item["name"].'</strong></td>';
echo '<td>'.$item["quantity"].'</td>';
echo '<td>$'.$item["quantity"]*$item["price"].'</td>';
// echo '<td><span id="'.$item["code"].'" class="remove"><i class="fa fa-minus-circle"></i></span></td>';
echo '</tr>';
$item_total += ($item["price"]*$item["quantity"]);
$quantity_total+=$item["quantity"];
}
echo '<tr>';
echo '<td><strong>Total</strong></td><td>'.$quantity_total.'</td><td>$'.$item_total.'</td>';
echo '</tr>';
echo '<tr>';
echo '<td></td>';
echo '<td><a data-toggle="tooltip" data-placement="bottom" title="Checkout" href="checkout.php"><button class="btn btn-success">
<i class="fa fa-shopping-cart fa-white"></i>
<span>Checkout</span>
</button></a></td>';
echo '<td></td>';
echo '</tr>';
echo '</table>';
}
else
{
echo '<h2 class="text-center"><i class="fa fa-shopping-cart"></i> Cart is empty!<br/>$0.00</h2>';
}
?>

This code will process all requests including item add, item delete, display added items will be shown by this code.
After completing this step our AJAX PHP Shopping Cart is now ready to execute. If everything appropriates this project will display like AJAX PHP Shopping Cart with jQuery Demo. Yes, we have already completed many steps and need to pass some steps to complete this project fully. Now, we are going to create a checkout page to complete users order. checkout page will display users selected products only and they could place orders from here. so now create a checkout.php file and write down this code.
checkout.php
<?php
@session_start();
require_once("db.class.php");
$db_handle = new DBactions();
echo '<!DOCTYPE html>';
echo '<html lang="en">';
echo '<head>';
echo '<meta charset="utf-8">';
echo '<meta http-equiv="X-UA-Compatible" content="IE=edge">';
echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
echo '<title>My Products - Checkout</title>';
echo '<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">';
echo '<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">';
echo '<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>';
echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>';
echo '<link href="asset/styles.css" type="text/css" rel="stylesheet" />';
echo '<script src="asset/scripts.js" type="text/javascript"></script>';
echo '</head>';
echo '<body>';
echo '<div class="container">';
echo '<header class="bg-primary text-center">Checkout</header>';
echo '<div class="row">';
echo '<div class="col-lg-8 col-md-8 col-sm-12">';
echo '<div class="bg-success text-center peoduct-header">My Products</div>';
if(isset($_SESSION["products"])){
echo '<div class="row">';
foreach ($_SESSION["products"] as $item){
echo '<div class="col-lg-4 col-md-4 col-sm-12 text-center">';
$product = $db_handle->runAssoc("SELECT * FROM products WHERE code ='".$item["code"]."'");
echo '<div class="product-image"><img src="'.$product['image'].'"></div>';
echo '<div class="product-name">'.$item["name"].'</div>';
echo '<div class="product-price">$'.$item["price"].'</div>';
echo '<div><input type="number" class="quantity '.$item["code"].'" name="quantity" value="'.$item["quantity"].'" size="2"></div>';
echo '<span id="'.$item["code"].'" class="cart add"><i class="fa fa-cart-plus"></i></span>';
echo ' <span id="'.$item["code"].'" class="remove added"><i class="fa fa-minus-circle"></i></span>';
echo'</div>';
}
echo '</div>';
}
echo '</div>';
echo '<div class="col-lg-4 col-md-4 col-sm-12">';
echo '<div class="bg-success text-center peoduct-header">';
echo '<i class="fa fa-cart-arrow-down"></i> Your Shopping Cart <span class="badge empty"><i class="fa fa-trash-o"></i> Empty</span></div>';
echo '<div id="mycart" class="cart-items"></div>';
echo '<div class="text-center"><button class="btn btn-primary">Place Order</button></div>';
echo '</div>';
echo '</div>';
echo '<span id="notification"></span>';
echo '<footer class="bg-primary text-center">&copy; phpans.com</footer>';
echo '</div>';
echo '</body>';
echo '</html>';
?>


We have added all scripts now we need to do a simple job. We added some product image link with database table now ensure about image directory. We placed all images into product-images directory. So ensure this directory really exists with entire images which were added into products table.
Now run this script on a server. I hope it will work fine. Our AJAX PHP Shopping Cart with jQuery project is complete.

In this article, we made AJAX PHP Shopping Cart. You are free to download and modify the code as you wish and you can make your e-commerce website. I hope you understand this tutorial. If you have any question or comment about this AJAX PHP Shopping Cart with jQuery article please don't hesitate to do that, please comment your question in comment section.

Download PDF
Is this article helpful for you?
1 Comments
Adam August 24, 2016, 06:04
I'm sorry but this script is not OK to use in a production setting; you should never, NEVER trust user input, your code easily allows attackers to do SQL Injection attacks on this site. At the least, use prepared statements when doing database queries. You also don't have to echo every line of HTML, you can just close the PHP tag, and write html, even if your file ends in ".php". e.g.
Instead of:
echo '</body>';
echo '</html>';
Just write:
?>
</body>
</html>





captcha

  • Connect
  •       
Top
Create an free account and start learning & sharing! Sign Up