It 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.

jQuery Ajax Shopping Cart

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.

Other Add-To-Basket Tutorials Built on This Example:

To try the demo or download the script:

Download

The HTML

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 alt="Product1" src="images/product1.jpg" /></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&amp;productID=1" onclick="return false;"> <img alt="Add To Basket" height="32" id="featuredProduct_1" src="images/add-to-basket.gif" width="111" /> </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:

  • a link with onClick="return false; value which means it won't be active if JavaScript is active (to make the script unobtrusive)
  • add-to-basket image has an unique ID: id="featuredProduct_1" which we'll use to understand the button of which product is clicked

HTML For The Basket:

<div id="basketWrap">
	<div id="basketTitleWrap">Your Basket</div>
	<div id="basketItemsWrap">
		<ul>
			<li>&nbsp;</li>
<!--?php getBasket(); ?-->		</ul>
	</div>
</div>

The Highlights:

  • we have an empty <span> with id="notificationsLoader" to show a loading image
  • we keep an empty div to be able to insert any data before/after them
  • we call a PHP function: <?php getBasket(); ?> to get the basket data when the page is first loaded.

The JavaScript (jQuery)

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:

  • splitting the ID of the clicked "add-to-basket" image which is "featuredProduct_1" from the "_" character & get the databaseID of the product (1)
  • inserting the loader.gifimage inside the element with id="notificationsLoader"
  • posting a data with Ajax to our functions.php fil which handles all the server-side jobs. 2 data are posted: productID and the action to be done which is addToBasket
  • There are 2 possibilities when the data is posted, the items may already be inside the basket or it may be a new item. So, we have an if clause: if( $("#productID_" + productIDVal).length > 0){ which checks if an element with ID: productID1 (1 is a variable) exists in the page
    •  if it exist:
      • we change the opacity of that object to 0 (make it invisible)
      • load the new <li>product info</li> response that comes from the functions.php
      • remove the original <li>product info</li> object whose opacity was 0
      • and play with the new <li>product info</li> object's opacity to create a blinking effect
      • empty the contents inside id="notificationsLoader" to stop the loading animation
    • if it does not exist:
      • we insert the response from the functions.php before the first hidden <li> and hide it
      • then use jQuery's show function to display it with an effect
      • empty the contents inside id="notificationsLoader" to stop the loading animation

Function 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:

  • As the objects are inserted to basket via Ajax, the new HTML items inside the basket are normally not loaded to the DOM and we can't reach them via JavaScript. jQuery offers an event named "live" (starting from jQuery 1.3) which loads the new created items to the DOM. So we used this event.
  • All other tasks are similar to adding an item, we splitted the HTML element from the "_" character and got the productID to be deleted and sent it to functions.php via Ajax.

The Database

We have used a MySQL database in this example with 2 tables:

Products:

Add To Basket Products Table

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

Add To Basket Sessions Table

The PHP

There is nothing complicated on the PHP part.

Handle The Variables:

[sourcecode language=&"php"]
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;
}
}
[/sourcecode]

The Highlights:

  • we create a session variable so every different user will have their own baskets
  • understand if the request comes from a POST (Ajax) or GET (JS disabled) request and get the action & productID variables
  • if it is a GET request we change the value of a variable named $noJavaScript to 1

PHP 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:

  • we insert the product to the database. If $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:

  • we delete the product to the database. If $noJavaScript to 1 we redirect to the index.php

PHP 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);
		$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:

  • This is a standard PHP function which creates the HTML for the items in the basket with a loop

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.

Answerbase E-Commerce
WebResourcesDepot Feed