Web development , php , ajax , symfony, framework, zend
In: web resources
28 Jul 2009It is a clear fact that Ajaxed interfaces, if not overused, eases using websites so much.
For an e-commerce website, this can mean a better shopping experience for customers where they can concentrate more on the products which may result in better sales.

This is a detailed tutorial which shows creating an unobtrusive Ajaxed shopping cart using jQuery & PHP and can guide you to Ajaxify any e-commerce software you may already be using or coding.
The main functions of the cart will be adding/removing items to the basket without the need of refreshing the page & displaying the actions with effects.
To try the demo or download the script:
Rather than the formatting of the page, as you can design it however you prefer, we’ll be focusing on the vital parts which does all the tricks.
HTML For The Product’s Wrapper:
<div class="productWrap"> <div class="productImageWrap"> <img src="images/product1.jpg" alt="Product1" /> </div> <div class="productNameWrap"> Krups Coffee Maker </div> <div class="productPriceWrap"> <div class="productPriceWrapLeft"> $95 </div> <div class="productPriceWrapRight"> <a href="inc/functions.php?action=addToBasket&productID=1" onClick="return false;"> <img src="images/add-to-basket.gif" alt="Add To Basket" width="111" height="32" id="featuredProduct_1" /> </a> </div> </div> </div>
The part we’ll focus is the contents inside <div class="productPriceWrapRight"> which wraps the "add-to-basket" button.
The Highlights:
onClick="return false; value which means it won’t be active if JavaScript is active (to make the script unobtrusive)id="featuredProduct_1" which we’ll use to understand the button of which product is clickedHTML For The Basket:
<div id="basketWrap"> <div id="basketTitleWrap"> Your Basket <span id="notificationsLoader"></span> </div> <div id="basketItemsWrap"> <ul> <li></li> <?php getBasket(); ?> </ul> </div> </div>
The Highlights:
<span> with id="notificationsLoader" to show a loading image<?php getBasket(); ?> to get the basket data when the page is first loaded.We have 2 main jQuery functions:
Function For Adding To Basket:
$(".productPriceWrapRight a img").click(function() {
var productIDValSplitter = (this.id).split("_");
var productIDVal = productIDValSplitter[1];
$("#notificationsLoader").html('<img src="images/loader.gif">');
$.ajax({
type: "POST",
url: "inc/functions.php",
data: { productID: productIDVal, action: "addToBasket"},
success: function(theResponse) {
if( $("#productID_" + productIDVal).length > 0){
$("#productID_" + productIDVal).animate({ opacity: 0 }, 500, function() {
$("#productID_" + productIDVal).before(theResponse).remove();
});
$("#productID_" + productIDVal).animate({ opacity: 0 }, 500);
$("#productID_" + productIDVal).animate({ opacity: 1 }, 500);
$("#notificationsLoader").empty();
} else {
$("#basketItemsWrap li:first").before(theResponse);
$("#basketItemsWrap li:first").hide();
$("#basketItemsWrap li:first").show("slow");
$("#notificationsLoader").empty();
}
}
});
});
The Highlights:
loader.gifimage inside the element with id="notificationsLoader"productID and the action to be done which is addToBasketif( $("#productID_" + productIDVal).length > 0){ which checks if an element with ID: productID1 (1 is a variable) exists in the page
<li>product info</li> response that comes from the functions.php<li>product info</li> object whose opacity was 0<li>product info</li> object’s opacity to create a blinking effect id="notificationsLoader" to stop the loading animation id="notificationsLoader" to stop the loading animationFunction For Removing From Basket:
$("#basketItemsWrap li img").live("click", function(event) {
var productIDValSplitter = (this.id).split("_");
var productIDVal = productIDValSplitter[1];
$("#notificationsLoader").html('<img src="images/loader.gif">');
$.ajax({
type: "POST",
url: "inc/functions.php",
data: { productID: productIDVal, action: "deleteFromBasket"},
success: function(theResponse) {
$("#productID_" + productIDVal).hide("slow", function() {$(this).remove();});
$("#notificationsLoader").empty();
}
});
});
The Highlights:
productID to be deleted and sent it to functions.php via Ajax.We have used a MySQL database in this example with 2 tables:
Products:

Baskets (for keeping the shopping cart of every different session)

There is nothing complicated on the PHP part.
Handle The Variables:
session_start();
$sessionID = $_COOKIE['PHPSESSID'];
if($_POST['action'] != '' || $_GET['action'] != '') {
if($_POST['action'] == '')
{
$action = $_GET['action'];
$productID = $_GET['productID'];
$noJavaScript = 1;
} else {
$action = $_POST['action'];
$productID = $_POST['productID'];
$noJavaScript = 0;
}
}
The Highlights:
action & productID variables$noJavaScript to 1PHP For Add To Basket:
if ($action == "addToBasket"){
$productInBasket = 0;
$productTotalPrice = 0;
$query = "SELECT * FROM products WHERE productID = " . $productID;
$result = mysql_query($query);
$row = mysql_fetch_array( $result );
$productPrice = $row['productPrice'];
$productName = $row['productName'];
$query = "INSERT INTO baskets (productID, productPrice, basketSession) VALUES ('$productID', '$productPrice', '$sessionID')";
mysql_query($query) or die('Error, insert query failed');
$query = "SELECT * FROM baskets WHERE productID = " . $productID . " AND basketSession = '" . $sessionID . "'";
$result = mysql_query($query) or die(mysql_error());;
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$totalItems = $totalItems + 1;
$productTotalPrice = $productTotalPrice + $row['productPrice'];
}
if ($noJavaScript == 1) {
header("Location: ../index.php");
} else {
echo ('<li id="productID_' . $productID . '"><a href="inc/functions.php?action=deleteFromBasket&productID=' . $productID . '" onClick="return false;"><img src="images/delete.png" id="deleteProductID_' . $productID . '"></a> ' . $productName . '(' . $totalItems . ' items) - $' . $productTotalPrice . '</li>');
}
}
The Highlights:
$noJavaScript to 1 we redirect to the index.php else we create a <li> element including the product’s details & echo it so we can insert it via jQuery.PHP For Delete From Basket:
if ($action == "deleteFromBasket"){
$query = "DELETE FROM baskets WHERE productID = " . $productID . " AND basketSession = '" . $sessionID . "'";
mysql_query($query) or die('Error, delete query failed');
if ($noJavaScript == 1) {
header("Location: ../index.php");
}
}
The Highlights:
$noJavaScript to 1 we redirect to the index.phpPHP For Getting The Basket (For Initial Load)
Like mentioned before, we create a function to get the basket’s current situation, so it can be loaded in the initial loading of the page.
function getBasket(){
session_start();
$sessionID = $_COOKIE['PHPSESSID'];
$query = "SELECT * FROM baskets WHERE basketSession = '" . $sessionID . "' GROUP BY productID ORDER By basketID DESC";
$result = mysql_query($query);
//echo $query;
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$query2 = "SELECT * FROM products WHERE productID = " . $row['productID'];
$result2 = mysql_query($query2);
$row2 = mysql_fetch_array( $result2 );
$productID = $row2['productID'];
$productPrice = $row2['productPrice'];
$productName = $row2['productName'];
$query2 = "SELECT COUNT(*) AS totalItems FROM baskets WHERE basketSession = '" . $sessionID . "' AND productID = " . $productID;
$result2 = mysql_query($query2);
$row2 = mysql_fetch_array( $result2 );
$totalItems = $row2['totalItems'];
$basketText = $basketText . '<li id="productID_' . $productID . '"><a href=inc/functions.php?action=deleteFromBasket&productID=' . $productID . ' onClick="return false;"><img src="images/delete.png" id="deleteProductID_' . $productID . '"></a> ' . $productName . '(' . $totalItems . ' items) - $' . ($totalItems * $productPrice) . '</li>';
}
echo $basketText;
}
The Highlights:
And, the Ajaxed basket built with jQuery & PHP is ready-to-use.
P.S. To make the example work on your side, you should be creating a new database with the jBasket.sql file inside the download package & configure the database connection information inside “inc/db.php” file.
Special Downloads:
Ajaxed Add-To-Basket Scenarios With jQuery And PHP
Free Admin Template For Web Applications
jQuery Dynamic Drag’n Drop
ScheduledTweets
Advertisements:
SSLmatic – Cheap SSL Certificates (from $19.99/year)
Dreamhost $50 Discount Code: WRD
Follow WebResourcesDepot At Twitter And Get More Resources!
Tags: Javascript, Mysql, Php
This blog delivers stylish and dynamic news for designers and web-developers on all subjects of design, ranging from: CSS, Ajax, Javascript, web design, graphics, typography, advertising & much more. Our goal is to help you communicate effectively on the web with an engaging website or functional interface.