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
- 58 Comments

















58 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
@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.
Hello. great Job, any question . . when i want add more than 2 product in the basket this show …by example… Krups Coffee Maker(2 items) – $190…. OK… FINE…
but if i want delete only one item Krups Coffee Maker… the SCRIPT delete all item Krups Coffee Maker in the basket….
i think is very important a new textfield “amount “… and modify this script for delete item by item when the user does click on X (the red icon ) icon on the BASKET
Hi, 1st of Gr8 script, I’m having problems though with the if nojavascript then ../index.php since i’m working with a dynamic cartloading from a search result.
So that if a person clicks on the first item and adds it to cart he can stay on the same page but if he has deleted it from the cart whilst in the search page, it should not load back to index.php but to the search results page.
With this problem i’m having that even though jquery works with the sliding and all, once an item is added to cart, it starts to animate but resets instantly.
10x for your help
very good script, but it must have somewhere a total price. Which code we must add to display the total price?
where can I download the files?!?
@johnny,
You should be running a query for the items in the basket and displaying the item’s price*quantity after every add/delete action.
@$$$$,
Once subscribed to the RSS feed and wile reading any WRD article from the feed, you can find it under the title “Special Downloads” at the bottom of every article.
Great tut!! I have a question though. I am trying to implement something similar and was wondering where in the code dictates the added item will go on top in the cart or to the bottom?
Your demo shows the item going to the top. This is what I want to do however on my cart, it goes to the bottom. Which part of the code can I change to make this happen?
Thanks…
@Roy,
It is this part:
$(“#basketItemsWrap li:first”).before(theResponse);
which simply inserts the Ajax response before the first “li” element.
Thanks for the reply however my code is not exactly same as your code so I wouldn’t know where to put that.. Here is the snippet for mine. If you can point it out, that would be great!
`jQuery(‘a.add_product’).click( function() {
form_values = jQuery(“form”, jQuery(this).parent()).serialize();
jQuery.post( ‘index.php?ajax=true’, form_values, function(returned_data) {
eval(returned_data);
}
return false;
});
});
`
First of all thanks for the great script! I’ve troubles when cookies are disabled in a browser.
It’s possible then to insert records in the baskets-table with an empty basketSession-field. As a result those records are shown to every user to the website when calling getbaskets. Does anyone have a solution for this.
Thanks in advance
Hans
Hi!
I have one more GET variable in the action link of the product. How can i get it into this session of the JS file:
$(“.productPriceWrapRight a img”).click(function() {}
to send it with the $.ajax data?
Please give an example to get the href from the link at the same product you get the image information from. I know how to split it afterwards.
Best Regards
Robin
Hi,
I downloaded the files for this tutorial but when I execute the index.php file (I renamed it to index.htm?) the page loads but when I clicked the add to basket button, nothing happen to your basket table. maybe because of the database? I created the database but I don’t know how to make a connection? I am new to web programming. thanks.
Regards,
jay-arr
@jay-arr,
I suggest you check the response with Firebug which will probably help you view the error.
Great and aweson tutorial great for my new web site, thanks a lot buddy
demo page has error. plz fix it up. i need it now to implement in project.
@shekhar,
It is fixed both in demo and download.
Im trying to use this script for a favorite script, so i can select my favorite images, and it will display nicely on the sidebar. When i reload the page, my fav’s are still there, but when i close the page and then re-open, my fav list is empty. How can i fix this?
@Kim,
Sounds like you should be matching the list with the user via cookies, users own database id, etc. Simply, the common method you use the remember users.
I was working on it all day long, but still no luck:( Has anybody a pre-made script for the user problem??:$
Hello!
I have a problem.
In my shop product is always in the singular.
Need to hide the container when the product is placed in the basket and show it when the product is removed from the basket.
In advanced thanks!
@Slava,
You can accomplish it with the help of show/hide functions of jQuery.
I suggest digging this example: http://www.webresourcesdepot.com/ajaxed-sliding-shopping-cart-with-jquery/ as it has a similar functionality.
This is the best basket I have found.
I have found also a bug in the src-file: functions.php.
You have lost the string:
$row2 = mysql_fetch_array( $result2 );
before:
$totalItems = $row2['totalItems'];
in the function: getBasket().