iFUEL INTERACTIVE

A NY Interactive Agency and a Division of Agency212

See you on Flickr See you on Twitter See you on FaceBook Subscribe

Posts Tagged ‘jQuery’

jQuery, Magento and Ajax Add to Cart Redux
October 15th, 2009  |  12 COMMENTS  |  Development, Magento
Tags: , , , ,

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.


< ?php
include_once '../app/Mage.php';
Mage::app();

try{
     // usage /scripts/addToCartTest.php?product_id=838&amp;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;
}

Read more

Adding to the Cart with a jQuery Ajax Call in Magento
September 10th, 2009  |  9 COMMENTS  |  Development, Magento
Tags: , , ,

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.

Read more

Copyright iFuel Interactive © 2010. All Rights Reserved.
Going up? Click here.A NY INTERACTIVE AGENCY