My previous post on adding to the cart with ajax in Magento has generated enough interest – and pointed out enough flaws in my overly complex code – that I’ve decided to put together a simplified version, so here goes:
Step 1: Create the server side script.
My sample script is called “addToCartTest.php” and I put it in a /scripts folder in the root of my Magento installation.
<?php
include_once '../app/Mage.php';
Mage::app();
try{
// usage /scripts/addToCartTest.php?product_id=838&amp;amp;amp;amp;qty=1
$product_id = '';
// get query string
if (!isset($_GET['product_id'])) { $product_id = ''; } else { $product_id = $_GET['product_id']; }
if (!isset($_GET['qty'])) { $qty = '1'; } else { $qty = $_GET['qty']; }
$product = Mage::getModel('catalog/product')->load($product_id);
$session = Mage::getSingleton('core/session', array('name'=>'frontend'));
$cart = Mage::helper('checkout/cart')->getCart();
$cart->addProduct($product, $qty);
$session->setLastAddedProductId($product->getId());
$session->setCartWasUpdated(true);
$cart->save();
$result = "{'result':'success'}";
echo $result;
} catch (Exception $e) {
$result = "{'result':'error'";
$result .= ", 'message': '".$e->getMessage()."'}";
echo $result;
}
Step 2: Create the ‘html’ page
Obviously, you’d be putting this code into your product detail page or wherever you’re trying to add the item to the cart from.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Ajax add to cart sample</title>
<script src="/scripts/jquery-1.3.2.min-noconflict.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#buyNowButton").click(function(){
var qty = $("#qty").val();
var product_id = $("#buyNowButton").attr("product_id");
var params = "product_id=" + product_id + "&amp;amp;amp;amp;amp;amp;amp;amp;amp;qty=" + qty;
var result = $.getJSON("/scripts/addToCartTest.php", params, function(data, textStatus){
if (textStatus == "error"){
alert("There was an error adding this item to your cart. Please call customer service for assistance.", "Error");
return;
}
if (data.result == "error"){
alert("Sorry, an error occurred while adding the item to your cart. The error was: '" + data.message + "'");
return;
}
alert("Thanks! The item has been added to your cart!")
});
});
});
</script>
</head>
<body>
<input type="text" id="qty" value="1" />
<a id="buyNowButton" product_id="972" href="#">Buy Now</a>
</body>
</html>
That’s it!
Prerequisites:
1. jQuery (Because Magento uses prototype and scriptaculous, you have to use jQuery in “no conflict” mode);
I’ve included the source code, along with the no-conflict version of jQuery in the zip file attached.
Let me know if you’re using this code (helps my ego)!
=============================
“e-commerce done right”
http://www.ifuelinteractive.com
Punisher
Dude, you saved me a lot of time. Worked perfectly, no strings attached.
Thanks!
November 11, 2009 at 5:17 pm
molecule
Nice, any idea how to do this with configurable products?
Thanks
November 28, 2009 at 10:37 pm
Sam
Excellent stuff, works perfectly. Now to figure out how to update the cart totals on the page…gonna be jquery to the rescue me thinks!
December 3, 2009 at 7:16 am
munyah
dude you are the man. I just changed it slightly to work with prototype
thanks!!
December 8, 2009 at 6:33 am
Dylan
Cool script but it appears that this won’t work from a page that is not hosted on an external site. Thanks for posting.
December 18, 2009 at 1:34 pm
Dylan
I typed too fast. I was unable to get this script to work from a remote server (e.g. blog, website, etc.)
December 18, 2009 at 1:36 pm
Jon
I am going to use this, but I just did a quick test with some modifications to handle multiple products. Get in touch if you’d like to see my changes – but they are pretty simple. I just send multiple product ids and quantities to the php script (I use a single delimited string for each set of product ids and for quantities, then explode it on the server and add each item to the cart). Works great, thanks!
December 23, 2009 at 4:51 pm
Jason
Is this limited to any particular produce type(s)? I need a solution that will work for simple, configurable and bundled items, and this is definitely the most elegant method I’ve come across so far.
December 23, 2009 at 6:02 pm
omer
Thank you very much, greatly appreciated, we need more people like you helping us out with magento
February 23, 2010 at 5:04 pm
Joe
Hi, I am getting an error {‘result’:'error’, ‘message’: ‘Mage registry key “_singleton/core/session” already exists’} any ideas?
April 9, 2010 at 1:39 pm
Madhu
Hi..i have changed a bit and i am able to add multiple products..but prblm is i have to update mycart in the page(the div)..have u tried it?if so pls mail me.
Thank you!
May 5, 2010 at 12:17 am
Samir Rahan
The script worked great, but for some reason it messed up my sessions. Magento kept redirecting to the folder of the ajaxAddToCart files. Fixed the issue by renaming a value in app/etc/local.xml, not sure what happened though. any ideas? (more fix info here: http://www.yireo.com/tutorials/magento/magento-administration/280-unable-to-login-into-the-magento-backend)
May 21, 2010 at 12:45 am
Ravi
Let’s help your ego. It worked exactly as it mentioned. Great idea for basic starting. Thanks so much
July 16, 2010 at 11:37 am
Magento Themes
This is really a simple version. I have been using Magento for 3 years now and every time I look for something like this.
December 24, 2010 at 4:12 am
NiBa
Thx for sharing your approach! Your post helped me allot Im creating a complex product configurator within mage. At the end, I need a “add to cart” function of my created product and this snipet worked like a charm
January 25, 2011 at 6:04 am
NiBa
Some editions: for some reasons, the async way of using getJSON (wich is a short for jQuery.ajax()) wont work for my setting, so I used jQuery.ajax() with async:false to make the call.
In addition I found out parsing the result JSON oject with jQuery.parseJSON() will fail cause the result JSON is invalid. You have to use double quatation marks when building your JSON string within the PHP. Example:
$result = “{\”result\”:\”success\”}”;
January 26, 2011 at 9:48 am
Tom
Thanks for sharing! I ran into a couple of issues when interpreting the json result.
This seems to have done the trick:
$result = array('result'=>'success');
echo json_encode($result);
July 15, 2011 at 2:11 pm
arun
i have not got your coding pattern for add to cart.i have placed addToCartTest.php and jquery-1.3.2.min-noconflict.js of root in /script folder but where i would to put addToCartTest.html , i am not clear how to use this html file
can u please help how this script run perfectly for me ??
Thanks
September 11, 2011 at 4:09 am
selepok
Thank’s. Easy & perfect!
October 25, 2011 at 5:25 pm
Raj
Hi, first of all thanks for your good work.. its easy and fast to implement, but here is what i require.. i am on product listing page and i need to reflect the cart updated quantity in top menu and side as well. can you please help me out with the solution i am also trying to do so. any help will be appreciated.
Thanks
November 9, 2011 at 1:31 pm
Alexandre
Hi,
I’m actually using Magento for a school projet and I used your script. However i had to create some configurable products and i dunno how to implement it so that this script would work with this type of product. Would someone face the same issue and have a solution? Thx.
November 27, 2011 at 9:27 pm
Luis Fernando
If the product have options? How to use this? Thanks
December 12, 2011 at 9:04 pm
Patrol Hawk
Does this can work in magento 1.5 ? anyhow, I’m downloading to test it.
December 15, 2011 at 10:16 am