Magento Ajax Cart

Asked

Viewed 395 times

0

am having a problem in Gento.. with cart in ajax.. when I add or remove a product in cart.. the product is added and also deleted.. however.. it does not appear when I add.. or add when I delete... only with page Reload.. but no error appears in the console.. or in the log files.. apparently it’s all right.. the only thing that happens is that it returns successfully.. but does not display the product in the cart.. nothing. only when I re-load on the page... nor exclude when this is the case.

Someone can give me a light ?

when it removes.

{message: "Item was removed.", r: "success"}
message
:
"Item was removed."
r
:
"success"

when I add

{product_name: "Camiseta Fitness Don't Stop At Good Ref: 10094",…}
message
:
"Camiseta Fitness Don't Stop At Good Ref: 10094 was added into cart."
product_name
:
"Camiseta Fitness Don't Stop At Good Ref: 10094"
r
:
"success"

1 answer

1


I use this module to add the items to my cart

Download the jQuery Here

Save with the name jquery.js in Magento/js/jquery

Create a file called noconflict.js in /Magento/js/jquery and put this inside: jQuery.noConflict(); and save the file

Now let’s create our module

Create the respective folders Magento/app/code/local/{suaempresa}/Ajax
Within them create two more folders one call etc. and controllers

Within etc. create the file remember to replace the Your Company field
config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Suaempresa_Ajax>
            <version>0.1.0</version>
        </Suaempresa_Ajax>
    </modules>
    <frontend>
        <routers>
            <ajax>
                <use>standard</use>
                <args>
                    <module>Suaempresa_Ajax</module>
                    <frontName>ajax</frontName>
                </args>
            </ajax>
        </routers>
        <layout>
            <updates>
                <ajax>
                    <file>ajax.xml</file>
                </ajax>
            </updates>
        </layout>
    </frontend>   
    <global>
        <resources>
            <ajax_setup>
                <setup>
                    <module>Suaempresa_Ajax</module>
                </setup>
                <connection>
                    <use>core_setup</use>
                </connection>
            </ajax_setup>
            <ajax_write>
                <connection>
                    <use>core_write</use>
                </connection>
            </ajax_write>
            <ajax_read>
                <connection>
                    <use>core_read</use>
                </connection>
            </ajax_read>
        </resources>
    </global>
    <global>
        <rewrite>
            <ajax_cart> <!--This can be any unique id -->
                <from><![CDATA[#^/checkout/cart/#]]></from>  <!-- the URL which u want to override-->
                <to>/ajax/index/</to>  <!-- destination url -->
            </ajax_cart>
        </rewrite>
    </global>
</config>

Within controllers brood
Indexcontroller.php

<?php

require_once 'Mage/Checkout/controllers/CartController.php';
class Floresonline_Ajax_IndexController extends Mage_Checkout_CartController {

public function addAction()
    {
        $cart   = $this->_getCart();
        $params = $this->getRequest()->getParams();
        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'] = 'O item foi adicionado com sucesso';
                        $response['message'] = $message;
                    }
                }
            } catch (Mage_Core_Exception $e) {
            if ($this->_getSession()->getUseNotice(true)) {
                $this->_getSession()->addNotice(Mage::helper('core')->escapeHtml($e->getMessage()));
            } else {
                $messages = array_unique(explode("\n", $e->getMessage()));
                foreach ($messages as $message) {
                    $this->_getSession()->addError(Mage::helper('core')->escapeHtml($message));
                }
            }

            $url = $this->_getSession()->getRedirectUrl(true);
            if ($url) {
                $this->getResponse()->setRedirect($url);
            } else {
                $this->_redirectReferer(Mage::helper('checkout/cart')->getCartUrl());
            }
            } 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;
        }else{
            return parent::addAction();
        }
    }

    public function optionsAction(){
        $productId = $this->getRequest()->getParam('product_id');
        // Prepare helper and params
        $viewHelper = Mage::helper('catalog/product_view');

        $params = new Varien_Object();
        $params->setCategoryId(false);
        $params->setSpecifyOptions(false);

        // Render page
        try {
            $viewHelper->prepareAndRender($productId, $this, $params);
        } catch (Exception $e) {
            if ($e->getCode() == $viewHelper->ERR_NO_PRODUCT_LOADED) {
                if (isset($_GET['store'])  && !$this->getResponse()->isRedirect()) {
                    $this->_redirect('');
                } elseif (!$this->getResponse()->isRedirect()) {
                    $this->_forward('noRoute');
                }
            } else {
                Mage::logException($e);
                $this->_forward('noRoute');
            }
        }
    }

    protected function _getWishlist($wishlistId = null)
    {
        $wishlist = Mage::registry('wishlist');
        if ($wishlist) {
            return $wishlist;
        }
        try {
            if (!$wishlistId) {
                $wishlistId = $this->getRequest()->getParam('wishlist_id');
            }
            $customerId = Mage::getSingleton('customer/session')->getCustomerId();
            $wishlist = Mage::getModel('wishlist/wishlist');

            if ($wishlistId) {
                $wishlist->load($wishlistId);
            } else {
                $wishlist->loadByCustomer($customerId, true);
            }

            if (!$wishlist->getId() || $wishlist->getCustomerId() != $customerId) {
                $wishlist = null;
                Mage::throwException(
                    Mage::helper('wishlist')->__("Requested wishlist doesn't exist")
                );
            }

            Mage::register('wishlist', $wishlist);
        } catch (Mage_Core_Exception $e) {
            Mage::getSingleton('wishlist/session')->addError($e->getMessage());
        } catch (Exception $e) {
            Mage::getSingleton('wishlist/session')->addException($e,
            Mage::helper('wishlist')->__('Cannot create wishlist.')
            );
            return false;
        }

        return $wishlist;
    }
    public function addwishAction()
    {

        $response = array();
        if (!Mage::getStoreConfigFlag('wishlist/general/active')) {
            $response['status'] = 'ERROR';
            $response['message'] = $this->__('Wishlist Has Been Disabled By Admin');
        }
        if(!Mage::getSingleton('customer/session')->isLoggedIn()){
            $response['status'] = 'ERROR';
            $response['message'] = $this->__('Please Login First');
        }

        if(empty($response)){
            $session = Mage::getSingleton('customer/session');
            $wishlist = $this->_getWishlist();
            if (!$wishlist) {
                $response['status'] = 'ERROR';
                $response['message'] = $this->__('Unable to Create Wishlist');
            }else{

                $productId = (int) $this->getRequest()->getParam('product');
                if (!$productId) {
                    $response['status'] = 'ERROR';
                    $response['message'] = $this->__('Product Not Found');
                }else{

                    $product = Mage::getModel('catalog/product')->load($productId);
                    if (!$product->getId() || !$product->isVisibleInCatalog()) {
                        $response['status'] = 'ERROR';
                        $response['message'] = $this->__('Cannot specify product.');
                    }else{

                        try {
                            $requestParams = $this->getRequest()->getParams();
                            if ($session->getBeforeWishlistRequest()) {
                                $requestParams = $session->getBeforeWishlistRequest();
                                $session->unsBeforeWishlistRequest();
                            }
                            $buyRequest = new Varien_Object($requestParams);

                            $result = $wishlist->addNewItem($product, $buyRequest);
                            if (is_string($result)) {
                                Mage::throwException($result);
                            }
                            $wishlist->save();

                            Mage::dispatchEvent(
                                'wishlist_add_product',
                            array(
                                'wishlist'  => $wishlist,
                                'product'   => $product,
                                'item'      => $result
                            )
                            );


                            $referer = $session->getBeforeWishlistUrl();
                            if ($referer) {
                                $session->setBeforeWishlistUrl(null);
                            } else {
                                $referer = $this->_getRefererUrl();
                            }
                            $session->setAddActionReferer($referer);

                            Mage::helper('wishlist')->calculate();

                            $message = $this->__('%1$s has been added to your wishlist.',
                            $product->getName(), Mage::helper('core')->escapeUrl($referer));

                            $response['status'] = 'SUCCESS';
                            $response['message'] = $message;

                            Mage::unregister('wishlist');

                            $this->loadLayout();
                            $toplink = $this->getLayout()->getBlock('top.links')->toHtml();
                            $sidebar_block = $this->getLayout()->getBlock('wishlist_sidebar');
                            $sidebar = $sidebar_block->toHtml();
                            $response['toplink'] = $toplink;
                            $response['sidebar'] = $sidebar;
                        }
                        catch (Mage_Core_Exception $e) {
                            $response['status'] = 'ERROR';
                            $response['message'] = $this->__('An error occurred while adding item to wishlist: %s', $e->getMessage());
                        }
                        catch (Exception $e) {
                            mage::log($e->getMessage());
                            $response['status'] = 'ERROR';
                            $response['message'] = $this->__('An error occurred while adding item to wishlist.');
                        }
                    }
                }
            }

        }
        $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
        return;
    }
    public function compareAction(){
        $response = array();

        $productId = (int) $this->getRequest()->getParam('product');

        if ($productId && (Mage::getSingleton('log/visitor')->getId() || Mage::getSingleton('customer/session')->isLoggedIn())) {
            $product = Mage::getModel('catalog/product')
            ->setStoreId(Mage::app()->getStore()->getId())
            ->load($productId);

            if ($product->getId()/* && !$product->isSuper()*/) {
                Mage::getSingleton('catalog/product_compare_list')->addProduct($product);
                $response['status'] = 'SUCCESS';
                $response['message'] = $this->__('The product %s has been added to comparison list.', Mage::helper('core')->escapeHtml($product->getName()));
                Mage::register('referrer_url', $this->_getRefererUrl());
                Mage::helper('catalog/product_compare')->calculate();
                Mage::dispatchEvent('catalog_product_compare_add_product', array('product'=>$product));
                $this->loadLayout();
                $sidebar_block = $this->getLayout()->getBlock('catalog.compare.sidebar');
                $sidebar_block->setTemplate('ajaxwishlist/catalog/product/compare/sidebar.phtml');
                $sidebar = $sidebar_block->toHtml();
                $response['sidebar'] = $sidebar;
            }
        }
        $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
        return;
    }
}

Create a file called ajaxwishlist.js in Magento/skin/frontend/rwd/default/js/ajaxwishlist
ajaxwishlist.js

function ajaxCompare(url,id){
    url = url.replace("catalog/product_compare/add","ajax/index/compare");
    url += 'isAjax/1/';
    jQuery('#ajax_loading'+id).show();
    jQuery.ajax( {
        url : url,
        dataType : 'json',
        success : function(data) {
            jQuery('#ajax_loading'+id).hide();
            if(data.status == 'ERROR'){
                alert(data.message);
            }else{
                alert(data.message);
                if(jQuery('.block-compare').length){
                    jQuery('.block-compare').replaceWith(data.sidebar);
                }else{
                    if(jQuery('.col-right').length){
                        jQuery('.col-right').prepend(data.sidebar);
                    }
                }
            }
        }
    });
}
function ajaxWishlist(url,id){
    url = url.replace("wishlist/index/add","ajax/index/addwish");
    url += 'isAjax/1/';
    jQuery('#ajax_loading'+id).show();
    jQuery.ajax( {
        url : url,
        dataType : 'json',
        success : function(data) {
            jQuery('#ajax_loading'+id).hide();
            if(data.status == 'ERROR'){
                alert(data.message);
            }else{
                alert(data.message);
                if(jQuery('.block-wishlist').length){
                    jQuery('.block-wishlist').replaceWith(data.sidebar);
                }else{
                    if(jQuery('.col-right').length){
                        jQuery('.col-right').prepend(data.sidebar);
                    }
                }
            }
        }
    });
}

Create a file called ajax.xml in
app/design/frontend/{seutema}/default/layout/

ajax.xml

<?xml version="1.0"?>
<layout version="0.1.0">
    <catalog_product_view translate="label">
        <reference name="head">
            <action method="addItem"><type>js</type><name>jquery/jquery.js</name></action>
            <action method="addItem"><type>js</type><name>jquery/noconflict.js</name></action>
            <action method="addItem"><type>skin_js</type><name>js/ajaxwishlist/ajaxwishlist.js</name></action> 
            <action method="addItem"><type>skin_js</type><name>js/fancybox/jquery.fancybox.js</name></action>
            <action method="addItem"><type>skin_js</type><name>js/fancybox/jquery.mousewheel-3.0.6.pack.js</name></action>  
            <action method="addCss"><stylesheet>js/fancybox/jquery.fancybox.css</stylesheet></action>
        </reference>
        <reference name='product.info'>
            <action method='setTemplate'>
                <template>ajax/catalog/product/view.phtml</template>
            </action>
        </reference>
        <reference name='product.info.addtocart'>
            <action method='setTemplate'>
                <template>ajax/catalog/product/view/addtocart.phtml</template>
            </action>
        </reference>
        <reference name='product.info.addto'>
            <action method='setTemplate'><template>ajax/catalog/product/view/addto.phtml</template></action>
        </reference>
    </catalog_product_view>

    <catalog_category_default>
        <reference name="head">
            <action method="addItem"><type>js</type><name>jquery/jquery.js</name></action>
            <action method="addItem"><type>js</type><name>jquery/noconflict.js</name></action>  
            <action method="addItem"><type>skin_js</type><name>js/ajaxwishlist/ajaxwishlist.js</name></action>
            <action method="addItem"><type>skin_js</type><name>js/fancybox/jquery.fancybox.js</name></action>
            <action method="addItem"><type>skin_js</type><name>js/fancybox/jquery.mousewheel-3.0.6.pack.js</name></action>  
            <action method="addCss"><stylesheet>js/fancybox/jquery.fancybox.css</stylesheet></action>
        </reference>
        <reference name='product_list'>
            <action method='setTemplate'><template>ajax/catalog/product/list.phtml</template></action>
        </reference>
    </catalog_category_default>
    <catalog_category_layered>
        <reference name="head">
            <action method="addItem"><type>js</type><name>jquery/jquery.js</name></action>
            <action method="addItem"><type>js</type><name>jquery/noconflict.js</name></action>
            <action method="addItem"><type>skin_js</type><name>js/ajaxwishlist/ajaxwishlist.js</name></action>
            <action method="addItem"><type>skin_js</type><name>js/fancybox/jquery.fancybox.js</name></action>
            <action method="addItem"><type>skin_js</type><name>js/fancybox/jquery.mousewheel-3.0.6.pack.js</name></action>
            <action method="addCss"><stylesheet>js/fancybox/jquery.fancybox.css</stylesheet></action>
        </reference>
        <reference name='product_list'>
            <action method='setTemplate'><template>ajax/catalog/product/list.phtml</template></action>
        </reference>
    </catalog_category_layered>

    <ajax_index_options>
        <reference name="root">
            <action method="setTemplate"><template>page/empty.phtml</template></action>
        </reference>
        <reference name="head">
            <action method="addItem"><type>js</type><name>jquery/jquery.js</name></action>
            <action method="addItem"><type>js</type><name>jquery/noconflict.js</name></action>
        </reference>
        <reference name="head">
            <action method="addJs"><script>varien/product.js</script></action>
            <action method="addJs"><script>varien/configurable.js</script></action>

            <action method="addItem"><type>js_css</type><name>calendar/calendar-win2k-1.css</name><params/><!--<if/><condition>can_load_calendar_js</condition>--></action>
            <action method="addItem"><type>js</type><name>calendar/calendar.js</name><!--<params/><if/><condition>can_load_calendar_js</condition>--></action>
            <action method="addItem"><type>js</type><name>calendar/calendar-setup.js</name><!--<params/><if/><condition>can_load_calendar_js</condition>--></action>
        </reference>
        <reference name="content">
            <block type="catalog/product_view" name="product.info" template="ajax/catalog/product/options.phtml">
                <!--
                <action method="addReviewSummaryTemplate"><type>default</type><template>review/helper/summary.phtml</template></action>
                <action method="addReviewSummaryTemplate"><type>short</type><template>review/helper/summary_short.phtml</template></action>
                <action method="addReviewSummaryTemplate"><type>...</type><template>...</template></action>
                -->

                <block type="catalog/product_view" name="product.info.addtocart" as="addtocart" template="ajax/catalog/product/view/addtocart.phtml"/>

                <block type="catalog/product_view" name="product.info.options.wrapper" as="product_options_wrapper" template="catalog/product/view/options/wrapper.phtml" translate="label">
                    <label>Info Column Options Wrapper</label>
                    <block type="core/template" name="options_js" template="catalog/product/view/options/js.phtml"/>
                    <block type="catalog/product_view_options" name="product.info.options" as="product_options" template="catalog/product/view/options.phtml">
                        <action method="addOptionRenderer"><type>text</type><block>catalog/product_view_options_type_text</block><template>catalog/product/view/options/type/text.phtml</template></action>
                        <action method="addOptionRenderer"><type>file</type><block>catalog/product_view_options_type_file</block><template>catalog/product/view/options/type/file.phtml</template></action>
                        <action method="addOptionRenderer"><type>select</type><block>catalog/product_view_options_type_select</block><template>catalog/product/view/options/type/select.phtml</template></action>
                        <action method="addOptionRenderer"><type>date</type><block>catalog/product_view_options_type_date</block><template>catalog/product/view/options/type/date.phtml</template></action>
                </block>
                        <block type="core/html_calendar" name="html_calendar" as="html_calendar" template="page/js/calendar.phtml"/>
                    </block>
                <block type="catalog/product_view" name="product.info.options.wrapper.bottom" as="product_options_wrapper_bottom" template="catalog/product/view/options/wrapper/bottom.phtml" translate="label">
                    <label>Bottom Block Options Wrapper</label>
                    <action method="insert"><block>product.tierprices</block></action>
                    <block type="catalog/product_view" name="product.clone_prices" as="prices" template="catalog/product/view/price_clone.phtml"/>
                    <action method="append"><block>product.info.addtocart</block></action>
                    <action method="append"><block>product.info.addto</block></action>
                </block>

                <block type="core/template_facade" name="product.info.container1" as="container1">
                    <action method="setDataByKey"><key>alias_in_layout</key><value>container1</value></action>
                    <action method="setDataByKeyFromRegistry"><key>options_container</key><key_in_registry>product</key_in_registry></action>
                    <action method="append"><block>product.info.options.wrapper</block></action>
                    <action method="append"><block>product.info.options.wrapper.bottom</block></action>
                </block>
                <block type="core/template_facade" name="product.info.container2" as="container2">
                    <action method="setDataByKey"><key>alias_in_layout</key><value>container2</value></action>
                    <action method="setDataByKeyFromRegistry"><key>options_container</key><key_in_registry>product</key_in_registry></action>
                    <action method="append"><block>product.info.options.wrapper</block></action>
                    <action method="append"><block>product.info.options.wrapper.bottom</block></action>
                </block>
                <action method="unsetCallChild"><child>container1</child><call>ifEquals</call><if>0</if><key>alias_in_layout</key><key>options_container</key></action>
                <action method="unsetCallChild"><child>container2</child><call>ifEquals</call><if>0</if><key>alias_in_layout</key><key>options_container</key></action>
            </block>
        </reference>
    </ajax_index_options>
</layout> 

Add to app/design/frontend/{seutema}/default/template/Catalog/product/view.phtml

        var productAddToCartForm = new VarienForm('product_addtocart_form');
                    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');
                        }
                        url = url.replace("checkout/cart","ajax/index"); 
                        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);
                                        if(jQuery('.block-cart')){
                                            jQuery('.block-cart').replaceWith(data.sidebar);
                                        }
                                        if(jQuery('.header .links')){
                                            jQuery('.header .links').replaceWith(data.toplink);
                                            window.location.href = '<?php echo Mage::getUrl("checkout/cart");?>';
                                        }
                                  }
                            });
                        } catch (e) {
                        }

        //End of our new ajax code
                        this.form.action = oldUrl;
                        if (e) {
                            throw e;
                        }

                        if (button && button != 'undefined') {
                            button.disabled = true;
                        }
                    }
                }.bind(productAddToCartForm);
  • Speak my brother.. Quiet?! then bro I already solved the problem.. but I gave you a moral there anyway for having wasted a little of your time trying to help me! the problem was in a module configuration that I was not seeing bro.. needed to enter some information there and voila.. all working again! success brother.

  • Quiet! No problem, anything you need! Hugs, success!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.