iFuel is Now Part of the Amsive Family! Read More

jQuery, Magento and Ajax Add to Cart Redux

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:

ajaxAddToCart.zip

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.

[sourcecode language='php']

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;
}
[/sourcecode]


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.

[sourcecode language='html']




Ajax add to cart sample




     
     Buy Now



[/sourcecode]

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

26 Responses to “jQuery, Magento and Ajax Add to Cart Redux”

  1. 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!

  2. 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!

  3. 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 🙂

  4. 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”}”;

  5. 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);

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

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

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

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>