Creating A Slick Ajaxed Add-To-Basket With jQuery And PHP

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.

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:
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 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:
- 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 <span id="notificationsLoader"></span> </div> <div id="basketItemsWrap"> <ul> <li></li> <?php getBasket(); ?> </ul> </div> </div>
The Highlights:
- we have an empty
<span>withid="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 withid="notificationsLoader" - posting a data with Ajax to our functions.php fil which handles all the server-side jobs. 2 data are posted:
productIDand the action to be done which isaddToBasket - 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
- if it exist:
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
productIDto 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:

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

The PHP
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:
- 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&productIDvariables - if it is a GET request we change the value of a variable named
$noJavaScriptto 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
$noJavaScriptto 1 we redirect to the index.php else we create a <li> element including the product’s details &echoit 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
$noJavaScriptto 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);
$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:
- 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.

Demo: http://webresourcesdepot.com/wp-content/uploads/file...
- Tags: Javascript Mysql Php
- Filed under: E-Commerce, Extras, MIT License, No License, Tutorials
- 38 Comments






















38 Responses for "Creating A Slick Ajaxed Add-To-Basket With jQuery And PHP"
Good stuff, I can definitely use this for an order page I’m making. But, although being a loyal RSS reader, where can I find the DL link? And how do you know I am that loyal RSS reader?
thanks anyway, keep up the good work!
(also, your /images/ButtonTransparent.png down here looks a bit squeezed)
@Ronald,
Happy to hear that it may be helpful.
For the download:
When reading the latest post via RSS (this post in this case), at the bottom of the post, there is a title: “Special Downloads”. It is the first item under that title: “Ajaxed Add-To-Basket Scenarios With jQuery And PHP”.
Ok, yep, clever one. I usually scan the RSS intros in Google Reader and then click through to your site, so never noticed that, my bad …
This is an awesome tutorial. Very detailed, thanks much.
I’m not that into jquery, only used it with scripts I had found but I think I understood how all the logic works.
Great job, keep up.
@Ronald,
that’s ok, np.
For the /images/ButtonTransparent.png, can I ask which OS & browser you’re using so I can check it better? Thanks.
Nice tutorial!
With a checkout on the back end this will be very useful :0)
Very easy to follow tutorial with AMAZING results! Thanks for sharing, huge fan of the blog.
@Umut, bugger, I made a screenprint, but deleted it because it’s fine now. It actually was the squeezed “Share and support” button: http://www.webresourcesdepot.com/wp-content/themes/default/images/share-support.png rather than the “Post your comment” button. Using Vista and Firefox.
But like I said, it’s ok now. Maybe a caching issue.
@Ronald,
It can be about caching. Thanks very much for the effort.
I think this beats nettuts! A great website with great links! Thanks
@Kiran,
Nettuts is a great website with quality content and both sites are very different than each other.
And, thanks that you like the content at WRD.
Awesome tutorial.
Very detailed explanation. I liked the session entry in db to provide each user his own cart.
I love it.
[...] Panier e-commerce jQuery et PHP [...]
What i must do if i want to clear the basket and to show the total price off all products ?
Thanks
@andreas,
I think the best options would be:
- sending a request similar to deleting 1 product but the PHP page should be coded to delete all..
- wrapping the prices of the products in a with a special class and finding th esum of the contents of the objects with that class..
These will easily complete what you need but requires some coding. Hope the ideas help.
I’m trying to implement your script which is great!
I’m having issues with the animation aspect and was wondering if you had a similer issue?
Thanks
@Martin,
I didn’t face that. If you can you open the problem you’re facing in detail maybe me or an other reader may help.
Nice tutorial, but i’m wondering what do you do with all those records in the basket table when a session expires?
@JKL,
It can be a good idea to delete the ones which are older than x days via a cron job.
I’m a little confused… At what point does this code set the basket variable PHPSESSID? From what I can tell there is no where it is explicitly set.
I don’t know what I did wrong, but I have a problem with animation. When I add a product to my basket sometimes it doesn’t update quantity, but adds another line to my basket even if this kind of product already stored there. It gets fixed, products are grouped together, when I reload the page.
I apologize, it was my bad =)
very nice stuff, i would like to add a checkout options at the end where customer fills in his/her details and the details will be send to email? how can i do that, is there any tutorial or scripts ?
@kale,
The code only presents the “add to basket” part and you must be hardcoding that functionality.
Thanks for the reply back. The issue can be seen at:
http://www.hpieurope.com/clearance/ which is a test site I implemented the script into. If you add an item into the basket it wont show the animation but will add it to the basket when the page has refreshed.
Thanks
Martin
Could anybody help out please?
How can i modify this so that if the basket is empty it displays a message saying “your basket is empty. blah blah blah” This disappears when you add the first product, and would reappear if you removed all products from your basket
Many thanks
/Adam
@Adam,
There are 3 things you have to modify:
- The initial load of the cart which is done by the PHP file’s getBasket function: you should change it to generate a ” there are no items” text if there are no records.
- JavaScript part’s:
There is 1
So, after adding or removing the number of
When removing items
if $(“#basketItemsWrap> li”).size() < 2 {
$("#thedivmessagewillbedisplayed").html("There are no items")
}
if $("#basketItemsWrap> li”).size() > ” {
$(“#thedivmessagewillbedisplayed”).html(“”)
}
Hope it helps.
@Martin,
Although not sure, it must be something with the PHP file not generating the HTML to be inserted. Suggest checking that part.
Great Cart, but i’m having an issue with the getBasket() on line 74.
I’m getting this “Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource”
I can add items to the basket fine, but if i refresh the browser, I cannot get it to show the items in the cart. Once I add an item to the cart, it will show items, but initially it will not show what’s in my cart.
not posting any code, because I haven’t changed anything to the initial downloaded code. Just having trouble getting it to work like the demo.
Crackin example… Problem I have is this… I’m using your standard example which works perfectly (as they all do) in Firefox, but its failing in IE. When I say failing its adding duplicate values, 1 click to “Add to Basket” adds 2 items. The version of IE is 7 but I can’t see any reason why this would be the case.
Using xammp as the Apache, PHP and MySQL environment.
Hope this is a simple fix, ill look at it again and see if there is something im missing?
Cheers
Stevie
Great Jobs but php4 :s, its very hard to adapt this script on PHP5 object :s
See u late @ wrd ++
http://www.whitebloc.com
http://www.whitebloc.fr
[...] Creating A Slick Ajaxed Add-To-Basket With jQuery And PHP [...]
@JKL,
A lot about real marketing is about data. Un-purchased baskets are valuable pieces of data; A successful business will contantly anaylse every aspect of data to help refine a better website, a better deal and better income from more customers.
Peace
Thanks for this script

Do you know how can I modify this script to affich just the number of product in my cart (and not the detail) ?
Thanks
Is it possible to display in another place in the same page juste the “total number of product” in my basket ?
how can I integrate options for a product. For example shirt sizes: small, Medium, Large, XL
I also, wanted to have the end user enter a price that they want to pay for the product…this is wierd, but I am a not for profit and we have to suggest a donation and the end user has to put in what they want.
Thanks in advance. This is a sweet example.
Great Script! Is it possible that user enter a price for product? It would be very helpful fo me.
Thanks in advance.
@Chris & @Anes,
You can add any extra input.
After adding input fields, you’ll need to improve the line below to handle the values of new inputs (check how productIDVal is created) and handle them on the PHP side too.
data: { productID: productIDVal, action: “addToBasket”},
Bests.