Add Product to Shopping Cart using Ajax

In this blog post, i will show how to add product to shopping cart using ajax, we will use jQuery library for ajax operations

By default, in magento the add to cart process is a simple form submit, so the page get reloaded. It would be much faster if we didn’t have to reload the entire page.
Attached is the source code for this blog’s module.

Module update for 1.9 magento version Download here
Modules for older version also on git
Ok lets start step by step.

Step1: Include jQuery on Product Page

First download jQuery and then place it inside /js/jquery folder, so path would be /js/jquery/jquery.js. Next create a javascript file called noconflict.js in the jquery folder (/js/jquery/noconflict.js) jQuery Folder Structure. Write this code inside noconflict.js file

jQuery.noConflict();

Next open that catalog.xml layout file in your theme folder [app/design/frontend/base/default/layout/catalog.xml in default magento theme] and place this code inside tag <catalog_product_view>

<reference name="head">
        	<action method="addItem"><type>js</type><name>jquery/jquery-1.6.4.min.js</name></action>
        	<action method="addItem"><type>js</type><name>jquery/noconflict.js</name></action>
        </reference>

Now open any product page in your magento, and through firebug or chrome inspector, see if these two jquery files are included in your page.

Step2: Product Page

Next we need to make changes in product page, so that instead of form submit an ajax request is fired. To do this open the catalog/product/view.phtml file in your theme in default magento theme, the path is app\design\frontend\base\default\template\catalog\product\view.phtml
In this file you will find the javascript code as

 productAddToCartForm.submit = function(button, url) {
            if (this.validator.validate()) {
                var form = this.form;
                var oldUrl = form.action;

                if (url) {
                   form.action = url;
                }
                var e = null;
                try {
                    this.form.submit();
                } catch (e) {
                }
                this.form.action = oldUrl;
                if (e) {
                    throw e;
                }

                if (button && button != 'undefined') {
                    button.disabled = true;
                }
            }
        }.bind(productAddToCartForm);

change this code to

 productAddToCartForm.submit = function(button, url) {
            if (this.validator.validate()) {
                var form = this.form;
                var oldUrl = form.action;

                if (url) {
                   form.action = url;
                }
                var e = null;
//Start of our new ajax code
                if(!url){
                    url = jQuery('#product_addtocart_form').attr('action');
                }
                var data = jQuery('#product_addtocart_form').serialize();
                data += '&isAjax=1';	
                jQuery('#ajax_loader').show();
                try {
                    jQuery.ajax({
                    	  url: url,
                    	  dataType: 'json',
                    	  type : 'post',
                    	  data: data,
                    	  success: function(data){
                  	  		    jQuery('#ajax_loader').hide();
                  	  		    alert(data.status + ": " + data.message);
                  	  	  }
                    });
                } catch (e) {
                }
//End of our new ajax code
                this.form.action = oldUrl;
                if (e) {
                    throw e;
                }
            }
        }.bind(productAddToCartForm);

Next to do a little bit of styling go to phtml file catalog/product/view/addtocart.phtml
and then find this code there

<button type="button" title="<?php echo $buttonTitle ?>" class="button btn-cart" onclick="productAddToCartForm.submit(this)"><span><span><?php echo $buttonTitle ?></span></span></button>

change this to

<button type="button" title="<?php echo $buttonTitle ?>" class="button btn-cart" onclick="productAddToCartForm.submit(this)"><span><span><?php echo $buttonTitle ?></span></span></button>
<span id='ajax_loader' style='display:none'><img src='<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif')?>'/></span>

Now open your product page again and when you press the add to cart button, you should see a loading image + ajax request being sent.

Product Page Ajax Loading

Project Page Ajax Loading


Firebug View of Ajax Request

Firebug View of Ajax Request

Step3: Add to cart Controller

Next, we need to change the code at CartController.php in the addAction. Right now, we will directly change the core file, but later will show you how do this using magento best practices.
Open the class Mage_Checkout_CartController located at app\code\core\Mage\Checkout\controllers\CartController.php and find the addAction() function. In the addAction() you have the code,

$params = $this->getRequest()->getParams();

Just after this line place this code

if($params['isAjax'] == 1){
			$response = array();
			try {
				if (isset($params['qty'])) {
					$filter = new Zend_Filter_LocalizedToNormalized(
					array('locale' => Mage::app()->getLocale()->getLocaleCode())
					);
					$params['qty'] = $filter->filter($params['qty']);
				}

				$product = $this->_initProduct();
				$related = $this->getRequest()->getParam('related_product');

				/**
				 * Check product availability
				 */
				if (!$product) {
					$response['status'] = 'ERROR';
					$response['message'] = $this->__('Unable to find Product ID');
				}

				$cart->addProduct($product, $params);
				if (!empty($related)) {
					$cart->addProductsByIds(explode(',', $related));
				}

				$cart->save();

				$this->_getSession()->setCartWasUpdated(true);

				/**
				 * @todo remove wishlist observer processAddToCart
				 */
				Mage::dispatchEvent('checkout_cart_add_product_complete',
				array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
				);

				if (!$this->_getSession()->getNoCartRedirect(true)) {
					if (!$cart->getQuote()->getHasError()){
						$message = $this->__('%s was added to your shopping cart.', Mage::helper('core')->htmlEscape($product->getName()));
						$response['status'] = 'SUCCESS';
						$response['message'] = $message;
					}
				}
			} catch (Mage_Core_Exception $e) {
				$msg = "";
				if ($this->_getSession()->getUseNotice(true)) {
					$msg = $e->getMessage();
				} else {
					$messages = array_unique(explode("\n", $e->getMessage()));
					foreach ($messages as $message) {
						$msg .= $message.'<br/>';
					}
				}

				$response['status'] = 'ERROR';
				$response['message'] = $msg;
			} catch (Exception $e) {
				$response['status'] = 'ERROR';
				$response['message'] = $this->__('Cannot add the item to shopping cart.');
				Mage::logException($e);
			}
			$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
			return;
		}

Save the file and go back to the product page. Now add to cart using ajax should be functional. After clicking add to cart, you see a alert box with success message.

Step4: Update the My Cart Box + Top Links

Now, our ajax add to cart is working. But for the frontend user, the process is not very smooth. He just see a loading image and then an alert box. A better UI, would be if we are able to update the My Cart Box shown on right + the My Cart link shown at header. So lets see how to do that.

Magento Header Top Links
Magento Left Side Bar My Cart Box

For this first we need to change our javascript code we added in the view.phtml file. Change the jQuery.ajax function to

jQuery.ajax({
                    	  url: url,
                    	  dataType: 'json',
                    	  type : 'post',
                    	  data: data,
                    	  success: function(data){
                  	  		    jQuery('#ajax_loader').hide();
                  	  		    //alert(data.status + ": " + data.message);
                  	  		    if(jQuery('.block-cart')){
                  	  		    	jQuery('.block-cart').replaceWith(data.sidebar);
                  	  		    }
	                  	  		if(jQuery('.header .links')){
	              	  		    	jQuery('.header .links').replaceWith(data.toplink);
	              	  		    }
                  	  	  }
                    });

and in our CartController.php addAction() method, put this new code instead of the old code

if($params['isAjax'] == 1){
			$response = array();
			try {
				if (isset($params['qty'])) {
					$filter = new Zend_Filter_LocalizedToNormalized(
					array('locale' => Mage::app()->getLocale()->getLocaleCode())
					);
					$params['qty'] = $filter->filter($params['qty']);
				}

				$product = $this->_initProduct();
				$related = $this->getRequest()->getParam('related_product');

				/**
				 * Check product availability
				 */
				if (!$product) {
					$response['status'] = 'ERROR';
					$response['message'] = $this->__('Unable to find Product ID');
				}

				$cart->addProduct($product, $params);
				if (!empty($related)) {
					$cart->addProductsByIds(explode(',', $related));
				}

				$cart->save();

				$this->_getSession()->setCartWasUpdated(true);

				/**
				 * @todo remove wishlist observer processAddToCart
				 */
				Mage::dispatchEvent('checkout_cart_add_product_complete',
				array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
				);

				if (!$this->_getSession()->getNoCartRedirect(true)) {
					if (!$cart->getQuote()->getHasError()){
						$message = $this->__('%s was added to your shopping cart.', Mage::helper('core')->htmlEscape($product->getName()));
						$response['status'] = 'SUCCESS';
						$response['message'] = $message;
//New Code Here
						$this->loadLayout();
						$toplink = $this->getLayout()->getBlock('top.links')->toHtml();
						$sidebar = $this->getLayout()->getBlock('cart_sidebar')->toHtml();
						$response['toplink'] = $toplink;
						$response['sidebar'] = $sidebar;
					}
				}
			} catch (Mage_Core_Exception $e) {
				$msg = "";
				if ($this->_getSession()->getUseNotice(true)) {
					$msg = $e->getMessage();
				} else {
					$messages = array_unique(explode("\n", $e->getMessage()));
					foreach ($messages as $message) {
						$msg .= $message.'<br/>';
					}
				}

				$response['status'] = 'ERROR';
				$response['message'] = $msg;
			} catch (Exception $e) {
				$response['status'] = 'ERROR';
				$response['message'] = $this->__('Cannot add the item to shopping cart.');
				Mage::logException($e);
			}
			$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
			return;
		}

Now, when you click on AddtoCart button, instead of alert, the MyCart Box + Top Links will get updated. So now the user experience is much better.

Proper Way to do Step3

Now going back to step3, as per magento best practices we should not change any core files. So, what we will do is, create a new module called Excellence_Ajax using module creator and then in the IndexController.php add an action addAction() and extend of controller with Mage_Checkout_CartController. So our class declaration becomes

class Excellence_Ajax_IndexController extends Mage_Checkout_CartController

Now we will change our javascript code at view.phtml so, that our new controller is called instead of magento’s default cart controller. So there is the new javascript code.

if(!url){
       url = jQuery('#product_addtocart_form').attr('action');
}
url = url.replace("checkout/cart","ajax/index"); // New Code

So we are just replacing checkout/cart with our controller path.
Next in the addAction we will write the exact same code, except in the else condition we will call the parent::addAction() function.

public function addAction()
	{
		$cart   = $this->_getCart();
		$params = $this->getRequest()->getParams();
		if($params['isAjax'] == 1){
                   ....same code as above
                }else{
                   return parent::addAction();
                }
         }

Bug Reported
1. The cart side bar that shows up, after adding product using ajax. The ‘x’ or remove button doesn’t work. [This bug has been fixed and module files have been updated.]
The above code has been tested for all product types in Magneto 1.6 version

  • Rama Krishna Peddinti

    Thank you very much for the code.

    • Manish Prakash

      Thanks :)

  • Daniel

    works great, thanks man! really good article

    • Manish Prakash

      Thanks :)

  • http://twitter.com/pantzan Pantelis Zanias

    hello, 

    i have magento ver. 1.5.1.0 and jquery-1.6.4.min.js doesnt showing up! what i must to do?..:)Thanks!

    • Manish Prakash

      Thanks for pointing this out. i have added the jquery files to the module. You can re download the module source files and you will find the javascript in it now.

      • http://twitter.com/pantzan Pantelis Zanias

        Thanks for the response!! :)
        At step 3 i add the code but not alert box with success message appear! it stacks in loading.. 

        • Manish Prakash

          Can you check if jquery is getting loaded on your site?
          Use firebug and if you see any error message on the console paste it here.

          • http://twitter.com/pantzan Pantelis Zanias

            After your fixes of jquery its working..
            I see that firebug have no errors but still not success message appear.

            p.s. 1) I downloaded your source code and i passed on my server app/..etc
                   2) Then i edit step by step my code

          • Manish Prakash

            can you send me URL of your product page?

          • http://twitter.com/pantzan Pantelis Zanias
          • Manish Prakash

            It seems to be working fine in my FireFox browser?

          • Manish Prakash

            attached image 

          • http://twitter.com/pantzan Pantelis Zanias

            yes and mine now… but shouldn’t be a pop up box? or not? :)

            additionally, when you click to remove the products from sidebar cart then it will say that you added a new product to cart.

          • Manish Prakash

            No there is no popup. you can see the cart box on right get updated automatically via ajax.

            If you want to add a popup alert, you can put in the alert() in the ajax success function. 

          • http://twitter.com/pantzan Pantelis Zanias

            ok thanks a lot! 
            and with sidebar cart ? when i click to remove the items it says alert that i added the item to cart which is wrong..

          • Manish Prakash

            Ok, your right. i will checkout this bug and fix it. 
            i will update the module source code when its fixed. 

          • http://twitter.com/pantzan Pantelis Zanias

            Thanks again! I will be waiting for your update.

            p.s. for pop up: 
                                        //alert(data.status + “: ” + data.message); 

            this one can be popup?

          • Manish Prakash

            Yes

          • http://twitter.com/pantzan Pantelis Zanias

            i am new in magento and i cant do it to work.. the pop up alert..:/

          • Manish Prakash

            what exactly do you want to show in the popup alert box?

          • http://twitter.com/pantzan Pantelis Zanias

            that this product which is choosen is in cart and then close automatically.. i guess! 

          • http://twitter.com/pantzan Pantelis Zanias

            i found something else.. in sidebar cart there is “edit product” which going to blank page! :)

          • Manish Prakash

            The edit issue must be related to your theme. it works fine in default magento theme. switch to default magento theme and check

          • http://twitter.com/pantzan Pantelis Zanias

            alert it doesn’t work..:/

          • Manish Prakash

            To show an alert box instead of this line
            //alert(data.status + “: ” + data.message);
            put in 
            alert(‘Product Added To Cart Successfully’);

          • Manish Prakash

            the bug has been fixed and update the source code. please download module again and test

          • http://twitter.com/pantzan Pantelis Zanias

            In sidebar cart this error appeared:

            Fatal error: Call to undefined method Mage_Catalog_Helper_Data::canApplyMsrp() in/home/cartrid/test/app/design/frontend/default/default/template/ajax/checkout/cart/sidebar/default.phtmlon line 4

          • Manish Prakash

            Ok, this is because your are not using magento version 1.6.

            Ok I will update the code again and post it

          • http://twitter.com/pantzan Pantelis Zanias

            ok! the bug will be fixed?:)

          • http://twitter.com/pantzan Pantelis Zanias

            Great! fixed! 

            One other question, Can we implement in categories that show all the products together?

            Thanks.

          • Manish Prakash

            You mean ajax in category pages.

            Yes I am going to write a blog on this soon

          • http://twitter.com/pantzan Pantelis Zanias

            Thank you very much.. i want to be a good developer like you someday..:)

            could you suggest me the right way?.. i want one platform to read the magento like zend studio.. 

          • Manish Prakash

            Well there is very tutorials for magento. That’s why I am writing this blog J so there a good place.

            You should go the module development series I have written.

          • http://twitter.com/pantzan Pantelis Zanias

            lets start studding then..:)
             

          • Manish Prakash

            I have updated another module for magento version 1.5 which you should download and test.
            I didn’t get time to test it so let me know if it works fine.

  • Parul

    Hello ,,,Can u help me ..i download ur both extension in one setup and its not working on product view page ….

    Please help me as soon as possible..

  • Christian

    when you remove a product from the cart, it adds the last product you just added!

    • Manish Prakash

      i will check this out.. are you deleting the product from cart page?

  • Rajasingh31

    Hi Manish , Nice to meeting you. I have used your ajax shopping cart code. It’ working fine. But i am getting one issues. 1) My product total qty is 10. i have added 10 qty in cart, but still i can able to add one more qty. When saw the cart page. IT showing error(not available qty). Again i can add one qty now showing not available qty in product details page. Then my cart section(top link has been hide). Please guide me))

  • Manan

    can this work with configurable product?

  • jb

    Hello Manish,
    Thank very much for your blog. Your tutorials are well detailed and very interesting.
    As i am a newbie with magento and not really a developper, i learned a lot and quickly reading your post.
    With your help i integrate ajax for the wishlist and compare block without problem (except one detail in the future : ajax for the compare removing function).
    About the cart, sorry i don’t find the way. Therefore i explain my little problem in case you could give me a clue.
    Arrived Step 2 :
    http://imageshack.us/photo/my-images/97/20111211191041.jpg/
    The request seems to be sent but the ajax success function don’t work and the loading image stay shown.
    Arrived step 4:
    http://imageshack.us/photo/my-images/18/20111211191458.jpg/
    As you see, the request doesn’t work anymore and the url ends at a 404 erreur.
    Thank you in advance, if you fond the time to orientate my research.
    jB

  • David Kreutzer

    Hi Manish,
    first of all thanx for your great work! The community really appreciates your effort!

    I have a question: Do you have some solution for an AJAX cart with the thumbnails of the products and the descriptions of it (in the sidebar-cart). I do also need a remove article button.

    Could you help me to implement that?

    Thanks in advance!
    David Kreutzer

  • Michael

    Perfect job you did here. Thank you very much.

    There is one bug. When i add something to the cart and then directly remove it from the cart (sidebar), the page reloads and the product added one time (this is normally happening by default).

    Do you have a fix for this?

  • Francesco Loddo

    Hi, i think there are a bug, if i try to modify the quantity of product in the modify link in checkout/cart, the page don’t reload the information ( checkout/cart/configure). It is possible to fix that ?

  • Francesco Loddo

    Hi, i think missing function updateItemOptionsAction() to complete this plugin correctly how we can do this ?

  • Anonymous

    I downloaded the source code and put it into the corresponding folders but it doesn’t work. Is there anything else I have to do, like include the module in a XML file???? Thanks for your support

  • http://twitter.com/Alladyce Lehlabile A Kekana

    Hi Manish,

    When I add the PHP code to the Magento core file (CartController.php) while following the instructions above it works fine but after using the files downloaded and placing them in the relevant folders the recently added items in the sidebar disappear. Any idea why this is happening?

    • Manish Prakash

      Module might not be installed properly

      • http://twitter.com/Alladyce Lehlabile A Kekana

        Thanks for the quick respond Manish. I just found a solution. In the XML file “config.xml” the sidebar block is being re-writting  just before the Helpers code is called.

        The code now works seamlessly. Isn’t the script suppose to show a message that the item has been added to the cart?

      • Tejas Solanki

        hi,

        i found an error on shopping cart page after installing your extension
        Delete product is working with siiderbar , but on shopping cart page delete not working because it is not redirecting properly on indexcontroller page deleteaction … pls give me some idea.

        Thank you and regards,
        Tejas Solanki.

    • gourav

      ..

      • gourav

        mm

        • gourav

          ff

          • gourav

            fsdddadad

  • Pingback: Magento One Page Checkout | Magento Media()

  • dima br

    Thank You very much for Your share. I’m student just studying. I have signed in to Your newsletter. Waiting for more professional articles.

  • priyashindhwani

    Hi Manish,

    First of all thanx for your great work! 
    I install your extension and it’s working g8t
    but there is some minor issue when i add to cart thought ajax cart and remove from mini cart it show me 404 error.
    Please help me.

    Thanks in advance….:(

  • Rajiv Ranjan

    Hi Manish,

    Thanks for  excellent extension.
    Earlier I had worked according to core code changes  and It was working fine.
    But, when I have installed in 1.5.1 it show error during Ajax response
    “Fatal error: Call to a member function toHtml() on a
    non-object in core/local/Excellence/Ajax/controllers/IndexController.php on line 55″Please help to solve this issue.Thanks in advance.

  • Foo

    When adding a product, if I exceed the quantity available in inventory, all of the top links disappear.  Bug? Fix?

  • Mohitwadhawan508

    gr8 work…

  • http://niallm1.com/ Niall Madhoo

    Hi! Thanks for this tutorial. Do you have a demo setup that I can see?

  • jaimin

     i have also same problem i am using magento community version 1.5.1.0 and once click on add to cart product is add to cart but it doesn’t work again. i think it is a bug.

  • jaimin

     i found the solution and our mistake add to cart is not working because of below two line in view.phtml jquery function.just remove this two line.
    if (button && button != ‘undefined’) {                   button.disabled = true;
                   }and your add to cart work fine.thanks manish for this wonderful post. and please update as soon as possible for remove product from cart through ajax.

  • asd

    Not working for magneto 1.6.0.1 pls help

  • vipul

    It is possible to Add to cart product in  product list page using this module 

    • http://www.facebook.com/manikmalhotra92 Manik Malhotra

      Just need to edit the list.phtml

  • Günther Bosch

    @300f40d9833e628d0b723e52341ef7c7:disqus That’s a good argument. Did you get any replies on that? I also want ajax cart from the product page. But I cant find any extension for that. All extensions work for the products listing page.

    • http://www.facebook.com/manikmalhotra92 Manik Malhotra

      This is for the product page itself.

      • Gouravgodha

         hello

    • Mayur kashyap

       hello

  • Roberto Llanos

     hello, some for magento version 1.7 or what changes should be to work properly? greetings and thanks

  • http://profile.yahoo.com/A6C2QFZPJWTWTKWCDKHOF7PRQ4 sri

    Hi,

        The module is working nice but I want to apply the same to related products also that are displayed in the product page how can I do it can you please help me with it.

     Thanks
    Srikanth

  • http://www.facebook.com/manikmalhotra92 Manik Malhotra

    What seems to be the problem?

  • http://www.facebook.com/manikmalhotra92 Manik Malhotra

    This modification will alert the user with the name of the added products, and if you’re using the default theme it’ll also update the side cart, but if you’re using some other theme with different cart block, then you’ll have to update that block.

  • http://www.facebook.com/people/Yiwei-Shen/100001481815324 Yiwei Shen

    Thank you for your share, it is a very useful blog for me.

  • gourav

    DD

    • gourav

      aadd

      • gourav

        adadadad

        • gourav

          adadadadad

          • gourav

            adadaddadadad

          • gourav

            hmhmmm

          • gourav

            sfsfsfsf

          • gourav

            adadadad

          • gourav

            adadadadadad

  • azhar

    Nice Work and works on all latest magento version. but it can not added the custom option value into cart . Can you help me for adding custom option type file into cart ajax based … thanks in advance

  • Sunil Motihar

    Thanks a ton man!!!!
    Really well laid out and explained. It’s so subtle. Made my life easier.
    Thanks thanks thanks thanks thanks thanks thanks thanks thanks :*

  • Sunil Motihar

    I have got a question. I added the functionality to display the cart even when there is an error. I just copy pasted the replaceWith to the error condition. Now what happens is when the stock quantity is exceeded in cart, the error message is displayed on the next “add to cart” instance. How to display that on the same instance. To put it in simple words, I dont want the add to cart button to work if the quantity that I have added exceeds the stock value.

  • http://www.facebook.com/loualvaro Alvaro Lou

    New version working on Magento 1.7+
    https://github.com/imloualvaro/ajax-add-cart-module-revisited-by-imLouAlvaro

    Thumbs UP and everyone will see.

    • adi

      the git is empty

      • http://www.facebook.com/loualvaro Alvaro Lou

        try this –> http://cl.ly/0T0Y07472540

        ps. working for default theme, maybe will need some changes @ checkout/cart/sidebar/default.phtml and catalog/product/view.phtml

        Gluck!

        • mcalvo

          there was a bug in Pasichnikroman code for delete action

          after
          if (!$this->_getCart()->getQuote()->getHasError()){

          you have to add

          $product = $this->_initProduct();
          $message = $this->__(‘%s was deleted from your shopping cart.’, Mage::helper(‘core’)->htmlEscape($product->getName()));

        • aditya kurniawan

          i am using grayscale theme what should I change to make it works?

  • test

    pls help me for same issue

  • http://www.facebook.com/rafique Daniel Rafique

    nice tutorial, i am currently using a dropdown mini cart in the header is there a way to trigger the dropdown when a product is added using this module?

  • Zaour

    Hello, yes it works on Magento 1.7+.

    But you need to copy follows functions from Mage_Checkout_CartController (/app/code/core/Mage/Checkout/Controllers/CartController.php into your new IndexController (Excellence_Ajax_IndexController):

    /**
    * Retrieve shopping cart model object
    *
    * @return Mage_Checkout_Model_Cart
    */
    protected function _getCart()
    {
    return Mage::getSingleton(‘checkout/cart’);
    }

    /**
    * Initialize product instance from request data
    *
    * @return Mage_Catalog_Model_Product || false
    */
    protected function _initProduct()
    {
    $productId = (int) $this->getRequest()->getParam(‘product’);
    if ($productId) {
    $product = Mage::getModel(‘catalog/product’)
    ->setStoreId(Mage::app()->getStore()->getId())
    ->load($productId);
    if ($product->getId()) {
    return $product;
    }
    }
    return false;
    }

    /**
    * Get checkout session model instance
    *
    * @return Mage_Checkout_Model_Session
    */
    protected function _getSession()
    {
    return Mage::getSingleton(‘checkout/session’);
    }

  • RashaadRamdeen

    Good stuff, gunna try this today!

  • http://twitter.com/jony1116 zhang weixiang

    There is an error/bug when some customers’ cart has out of stock products, and after click the addtocart button.It will show undefine message in product cart , and for category page,the top shoping cart would dispear.Is there any good solutions to solve this?
    I found it is caused at “if (!$cart->getQuote()->getHasError()){” at
    CartController.php

  • Phil

    Hi, any idea why IE9.0 tries to save the response instead of executing it? It only happens with IE…works well with Chrome and Firefox…please help me out, I’m clueless about this one. Running Magento CE 1.7.0.2. Apache Server 2.2.23

  • Phil

    I have an issue with internet explorer 9.0. When you add a product to the cart, instead of executing the script, it tries to download it as a file…Anybody have a solution for this. It doesn’t happen with Chrome or Firefox, only with IE9.0. Any help would be appreciated.

    Thanks

  • Chris

    Hi There, I have used this on my site but it doesnt seem to add backorder products to the cart when the enable back orders option is enabled in the Magento default config. Do I need to change something?

  • Manish Prakash

    Hi Atul,
    Yes it works

  • Manish Prakash

    Hi Nathan,

    Thanks, can you explain in detail so that i can get actual idea of what you want to accomplish.

  • francisco Muniz

    HEllo,
    Could I get some help. I was able to install it on my custom theme. I only have two issues.
    1. The mini cart is not being updated. But when i refresh i see the total updated
    2. Even when i refesh the mini cart is not showing the products, only the total. When I do check out it looks fine.

    Any help will be greatly apreaciated

    • francisco Muniz

      Please any help, I really need to get this working.

      Thank you.

  • Anshu Mishra

    Module is not working for wishlist products.

    Like i have added a product in wishlist, then from wishlist page i am clicking on edit link, then from this wishlist edit product page, when i am clicking “add to cart”, it is behaving differently.

    It is adding product to cart but also at same time ajax loader keeps on revolving and i cannot see anything added in cart untill and unless i refreshed the page.

    Thanks in advance.

  • Anshu Mishra

    Hi,

    It is not working for products in wishlist.

    Like i have added a product in wishlist, then from wishlist page i am
    clicking on edit link, then from this wishlist edit product page, when i
    am clicking “add to cart”, it is behaving differently.

    It is adding product to cart but also at same time ajax loader keeps
    on revolving and i cannot see anything added in cart untill and unless i
    refreshed the page.

    Thanks in advance.

  • Hitesh Pachpor

    Excellent blog. Thanks a ton! Works on Magento v1.6.2 flawlessly.

  • Abaij

    Great post and source code. It’s working on my site using magento 1.7.0.2. I want to make something like this to “Add to Cart” button in category product list. How can I do that?

  • pradeep

    how to edit if added configural product on cart in magento?

    when we update cart it added new product or increment quantity not update.

  • srikanth

    I am getting an error which says 400 Bad request. How to solve this.

  • Aruna

    Hi, Good job.Working excellent.But the problem is ReplaceWith…The items are added to the cart but its not showing in the sidebar and top link… It only works after the refreshment of the page..Please help me out

  • http://landersoptimized.com/ Cooper Maruyama

    really appreciate this but you guys REALLY need to get rid of those promotional comments that get added to my code when copy/pasting from here.. I just spent an hour trying to figure out why it wasn’t working and it ended up being the comment causing a bug :(

  • xubi.uit

    Thank you, very nice tut, it helpful for me :)

  • Rajesh

    Does it work for magento 1.8.0 version

  • Onkar Kubal

    Does it works on Magneto 1.8 CE

  • aditya kurniawan

    hi there right now I am add total_weight in my cart so my customer can see product weight. but it looks like my total_weight code in app/design/fronted/base/default/checkout/cart/sidebar.phtml is not updated.

    here is my code in sidebar.phtml

    getQuote()->getItemsCollection()->getItems();
    $product = Mage::getModel(‘catalog/product’);
    $total_weight=0;
    foreach ($items as $item)
    {
    $product = $item->getProduct();
    $qty = $item->getQty();
    $weight = $item->getWeight();
    if($product->isConfigurable()){
    $total_weight+=($weight*($qty-1));
    } else {
    $total_weight+=($weight*$qty);
    };
    }
    ?>

    it looks like I have to add additional code in cartcontroller.etc can you tell me where should I add this code?

    thanks

  • aditya magento

    hi nice extension there
    there right now I am add total_weight in my cart so my customer can see product weight. but it looks like my total_weight code in app/design/fronted/base/default/checkout/cart/sidebar.phtml is not updated.

    here is my code in sidebar.phtml

    getQuote()->getItemsCollection()->getItems();
    $product = Mage::getModel(‘catalog/product’);
    $total_weight=0;
    foreach ($items as $item)
    {
    $product = $item->getProduct();
    $qty = $item->getQty();
    $weight = $item->getWeight();
    if($product->isConfigurable()){
    $total_weight+=($weight*($qty-1));
    } else {
    $total_weight+=($weight*$qty);
    };
    }
    ?>

    it looks like I have to add additional code in cartcontroller.etc can you tell me where should I add this code?

    thanks

  • Vivek

    Hi,

    i am using script on product list page but the issue is that when i add any product in to the cart the the same product(always first product) will add every time.
    can anybody help ?

    Thanks

    vivek

  • Mitali Cyrus

    Hi, i wanted magento to display its success message when its done. and even though you have added it in your code, it didn’t show up, so i did this tweak in view.phtml, i hope it helps someone :

    jQuery.ajax({
    url: url,
    dataType: ‘json’,
    type : ‘post’,
    data: data,
    success: function(data){
    jQuery(‘.messages’).remove(); //removes any previous messages
    jQuery(‘#ajax_loader’).hide();
    //alert(data.status + “: ” + data.message);
    if(jQuery(‘.block-cart’)){
    jQuery(‘.block-cart’).replaceWith(data.sidebar);
    }
    if(jQuery(‘.header .toplinks’)){
    jQuery(‘.header .toplinks’).replaceWith(data.toplink);
    }
    jQuery(‘.container’).prepend(‘The product has been added to you cart.’);
    //add the message in the beginning of the container – feel free to replace ‘.container’ with your class

    }
    });

    and also some css tweak to animate it –

    .messages{
    height:0px;
    opacity:0;
    animation:slide 300ms;
    -webkit-animation:slide 7s ease;
    }
    @-webkit-keyframes slide{
    0%{
    height:0px;
    opacity:0;
    }
    20%{
    height:64px;
    opacity:1;
    }
    80%{
    opacity:1;
    height:64px;
    }
    100%{
    opacity:0;
    height:0px;
    }
    }

    I am sure you can figure out the rest of css with vendor prefixes..

    Let me know if there is a simpler way. thanx.

  • darneson

    Hi there, does this work wth file upload functionality?

    • petty

      Any answer on this Topic?

  • Ramesh

    Hi.

    I used your code. It working good. If i enable SSL from backend. Its not working. Ajax request gonna failed. Any solution

    • Bart

      In view.phtml and list.phtml, right under
      url = url.replace(“checkout/cart”,”ajax/index”); // New Code
      Add this:
      url = url.replace(“https://”,”http://”);

      Ajax cart with ssl will now work (tested on Magento 1.8.1).

      • Serhiy Korohoda

        Hi Bart, want to thank you for providing fix to cart pages with SSL. Adding url = url.replace(“https://”,”http://”); works perfectly with 1.9.0.1 Thank you once again!

  • Rupesh Yadav

    yess it is working the way it should nice job….

  • Krupa Parikh

    hi,

    Can you plz tell me how can I add Custom option type file into cart by your Add Product to cart using Ajax ?

    • petty

      Any answers?

  • NV Web Concept

    Hi,

    Thanks for your great work ;)

    However I’ve got a strange problem, I can click on my AddToCart button once, and it works perfectly, but if I click again without refreshing the page, nothing happens. The productAddToCartForm.submit() function is not fired…

    Do you have an idea please?

  • Sarah Robertson

    Does this code give a choice to continue shopping or go to a shopping cart after adding a product to cart? What if a customer wants to buy several products from 1 category and adds one of them to a shopping cart and then he is automatically redirected to it. So he has to push the back button and choose another product, add it and be redirected again and so on.
    I believe not many customers are ready to do that. So an options “Continue shopping” would be very useful. I can’t find the code for that so I’m choosing an extension. Currently I’m thinking about ajax cart by Amasty.

  • sherodesigns

    Quick question, if I may. On a child theme I notice: “Fatal error: Call to a member function toHtml() on a non-object in…” error when I try to load a standard checkout.xml in my child theme but when I keep it out of a child theme the module of yours works. I noticed this when I tried to move checkout.xml to child theme (to get checkout progress working) but it would disable the add to cart. I am using Magento 1.8. I figure it may be a theme issue but I had to wonder if there are ways this module impacts the checkout module that we should know about? Just curious. Ty.

  • mahiba

    nice it works for me

  • Ryan Johnson

    For people trying to do this on Magento 1.9, make sure you replace the ‘cart_sidebar’ block with ‘minicart_head’ as shown in http://magento.stackexchange.com/questions/29684/magento-1-9-cart-not-updating

  • Mahesh

    Hi,
    Looks promising for v 1.7 can I also use this for v 1.9 Magento ?

  • ashvinimarwal

    Hi Developers , please tell me how to get value from another custom field on product page and save it any varibale. i want to use it price total function

    Thank you in advance