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.
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”
https://www.amsive.com