Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Magento - Ajax Add to Cart In Product View & List Page

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 974
    Comment on it

    Add to Cart Functionality using Ajax in MAGENTO : Hello Readers, In order to add Ajax add to cart feature in your product view page, first you should need to know how add to cart button is working. In magento add to cart button is a simple form submit that redirect to the cart page.

     

    Redirect to the cart page is default functionality in magento which can be override  so that users continue shopping without redirecting product URL, Recently Most of the e-commerce website has change their add to cart button featured to gain more visitor.

     

    Ajax add to cart functionality allow user to add the product in mini-cart items without redirecting the page. This new feature  allow users to continue shopping without reloading the page & provide better user experience for customers.

     

    There are many free Extension in Magento website which may or may not be work.
    So, in this magento tutorial I will manually show how to add product in shopping cart from product view pag without any extension.

     

    Ajax Add To Cart From product view Page (View.phtml)

    Go to app\design\frontend\Current theme\default\template\catalog\product\view.phtml

    open view.phtml & find below Java Script code.

    Replace:

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

    with

    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;
                    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();
                                  if(jQuery('.block-cart')){
                                        jQuery('.block-cart').replaceWith(data.sidebar);
                                    }
                                    if(jQuery('.header .links')){
                                        jQuery('.header .links').replaceWith(data.toplink);
                                    }
                              }
                        });Add to Cart Functionality using Ajax in MAGENTO :
                    } catch (e) {
                    }
                    this.form.action = oldUrl;
                    if (e) {
                        throw e;
                    }
                }
            }.bind(productAddToCartForm);
           }.bind(productAddToCartForm);


     

    Next, Go to catalog/product/view/addtocart.phtml (current theme), Find below code there.

    Replace :

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

    with:

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

     

    Next step, Go to cart controller (path: app\code\core\Mage\Checkout\controllers\CartController.php)

    Open CartController.php & find the addAction() function.
    In the addAction function, find $params = $this->getRequest()->getParams(); & replace it with the below code.

    $params = $this->getRequest()->getParams();
    if($params['isAjax'] == 1){
                $response = array();
                try {
                    if (isset($params['qty'])) {
                        $filter = new Zend_Filter_LocalizedToNormalized(Add to Cart Functionality using Ajax in MAGENTO :
                        array('locale' => Mage::app()->getLocale()->getLocaleCode())
                        );
                        $params['qty'] = $filter->filter($params['qty']);
                    }
    
                    $product = $this->_initProduct();
                    $related = $this->getRequest()->getParam('related_product');
                    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();Add to Cart Functionality using Ajax in MAGENTO :
    
                    $this->_getSession()->setCartWasUpdated(true);
                    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;
            }

    Now, final step is to check whether this functionality is working or not in your current theme of magento project. Go to magento front end (product page). click on Add to Cart button, if mini cart is upadated without reloading page then this featured perfectly working in your magento version.
    This magento ajax add to cart featured has been tested by me in Magneto 1.9.2 version & it is perfectly working.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: