Adding to the Cart with a jQuery Ajax Call in Magento

So, Ajax being the thing and all, I was hunting for a way to add an item to the cart using an Ajax call in Magento.  Recently, I noticed there was a module that apparently does this, but either I hadn’t seen that or it didn’t exist yet when I wrote this, so I hacked my way through it.

PHP isn’t my primary language – I come from the ASP, ASP.Net, C# world, but Magento was compelling enough that I’ve taken the leap.  I’m sure there are lots of things I could be doing better/differently here so if you’ve got some suggestions, I’m all ears!

Add to Cart Page

So first I needed an “Add to Cart” page (called – addToCart.php) that could be called from the client.  This page returns a result in JSON format.  The actual page also returns related items so we can try to cross sell the user, but I’ve removed that in this sample to make it simpler.

[sourcecode language=’php’]

getIdBySku(“$sku”);
if ($product_id == ”) {
$session->addError(“Product Not Added
The SKU you entered ($sku) was not found.”);
}
}

$request = Mage::app()->getRequest();

$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;
}

[/sourcecode]

Buy Now Button

Then I need a “Buy Now” button that doesn’t do a post to the server that I can attach my jQuery code to.  I’ve added the sku as an attribute to the anchor because I have this in a page that has more than one product on the page and I need to know which product has been selected.

[sourcecode language=’html’]

12 Responses to “Adding to the Cart with a jQuery Ajax Call in Magento”

    • Sorry, should have included that. Common.php is where I have some shared functions. I simplified the code for this article when I originally posted it, so you shouldn’t actually need it anymore.

      I posted it in a folder off the root of my site, but you could really put it anywhere as long as you have the following line correct in your client script:

      var result = $.getJSON(“/scripts/addToCart.php”, params, function(data, textStatus){

      Thanks for the feedback. Really glad you found it helpful!

    • I have the addToCart.php in a folder off the root of my site (see previous comment and reply). Shouldn’t really matter where you have it as long as you have the getJSON call pointing to the right location.

  1. Hmmmm…still no joy getting this going. Does it require jQuery UI to work correctly?

    I placed the buy now link and the script in default/template/catalog/product/list.phtml. But I get an error if I don’t change $product to $_product as that’s what the default template uses. I’m guessing it’s because I’m not using a color selector, so that bits redundant?

    Also, I suppose the buy now button should have a class of “add-to-cart”? And that it needs to be used with the list view and not grid, as grid doesn’t use the “listing-item” class?

    Any chance you can strip out the custom attributes (#colorSelector) and just use the simplest setup in your example?

    • Hi Sam –

      I’ll try to put together a cleaner version of the code for you. Yes, I do use jquery.ui. I tried to simplify it for the original post and all I succeeded in doing was confusing people. Sorry!

      Andy

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>