2

I'm new to Magento, and have added a Quick View on the category page, so the customers can add to cart without clicking on the product page.

The AJAX is updating for the topbar and sidebar, but overrides when anything new is added, so it only shows the last product.

Also its not saving the shopping basket, so when you click on the shopping cart button, its says "SHOPPING BASKET IS EMPTY".

IndexController.php

<?php
require_once 'Mage/Checkout/controllers/CartController.php';
class Excellence_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();
$response['message'] = $this->__('test');
                $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 (!$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_block = $this->getLayout()->getBlock('cart_sidebar');
                    Mage::register('referrer_url', $this->_getRefererUrl());
                    $sidebar = $sidebar_block->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;
        }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');
            }
        }
    }

}

List.phtml

<?php
/**
 * Product list template
 *
 * @see Mage_Catalog_Block_Product_List
 */
?>
<?php
    $_productCollection=$this->getLoadedProductCollection();
    $_helper = $this->helper('catalog/output');
?>
<?php
$this->_productCollection
->addAttributeToSelect('news_from_date')
->addAttributeToSelect('news_to_date');
?>
<?php if(!$_productCollection->count()): ?>
<p class="note-msg"><?php echo $this->__('There are no products matching the selection.') ?></p>
<?php else: ?>
<div class="category-products">
    <?php echo $this->getToolbarHtml() ?>
    <?php // List mode ?>
    <?php if($this->getMode()!='grid'): ?>
    <?php $_iterator = 0; ?>
    <ul class="products" id="products-list">
    <?php foreach ($_productCollection as $_product): ?>
        <li class="item<?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">
            <div class="listing-inner">
            <?php // Product Image ?>
            <div class="list-image">
            <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image"><img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(500); ?>"  alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" /></a>
            </div>
            <?php // Product description ?>
            <div class="listing-middle">
                <div class="listing-middle-inner">
                    <?php $_productNameStripped = $this->stripTags($_product->getName(), null, true); ?>
                    <h2 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $_productNameStripped; ?>"><?php echo $_helper->productAttribute($_product, $_product->getName() , 'name'); ?></a></h2>
                    <?php if($_product->getRatingSummary()): ?>
                    <?php echo $this->getReviewsSummaryHtml($_product) ?>
                    <?php endif; ?>

                    <div class="desc std">
                        <?php echo $_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description') ?>
                        <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $_productNameStripped ?>" class="link-learn"><?php echo $this->__('Learn More') ?></a>
                    </div>

                </div>
            </div>
            <div class="listing-right">
                    <?php echo $this->getPriceHtml($_product, true) ?>
                    <?php if($_product->isSaleable()): ?>
                        <p class="listing-add-button"><button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button></p>
                    <?php else: ?>
                        <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
                    <?php endif; ?>
                    <ul class="add-to-link">
                        <?php if ($this->helper('wishlist')->isAllow()) : ?>
                            <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist"><span></span><?php echo $this->__('Add to Wishlist') ?></a></li>
                        <?php endif; ?>
                        <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
                            <li><a href="<?php echo $_compareUrl ?>" class="link-compare"><span></span><?php echo $this->__('Add to Compare') ?></a></li>
                        <?php endif; ?>
                    </ul>
            </div>
            </div>
        </li>
    <?php endforeach; ?>
    </ul>


    <?php else: ?>

    <?php // Grid Mode ?>

    <?php $_collectionSize = $_productCollection->count() ?>
    <?php $_columnCount = $this->getColumnCount(); ?>

        <ul class="products-grid">
    <?php $i=0; foreach ($_productCollection as $_product): ?>
        <?php if ($i++%$_columnCount==0): ?>

        <?php endif ?>
            <li class="item<?php if(($i-1)%$_columnCount==0): ?> first<?php elseif($i%$_columnCount==0): ?> last<?php endif; ?>"><div class="item-inner">


                <div class="product-image-wrapper"> <button type="button" title="<?php echo $this->__('Quick View') ?>" class="button btn-quick-view" onclick="showOptions('<?php echo $_product->getId()?>')"><span><i class="triangle-topleft"></i><i class="triangle-bottomleft"></i><span><?php echo $this->__('Quick View') ?></span></span></button>
                        <a href='<?php echo $this->getUrl('ajax/index/options',array('product_id'=>$_product->getId()));?>' class='ajax-fancybox' id='fancybox<?php echo $_product->getId()?>' style='display:none'>Test</a><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image"><img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(500); ?>" width="500" height="500" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" /></a>
                   <ul class="add-to-link">
                        <?php if ($this->helper('wishlist')->isAllow()) : ?>
                            <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></li>
                        <?php endif; ?>
                        <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
                            <li><a href="<?php echo $_compareUrl ?>" class="link-compare"><?php echo $this->__('Add to Compare') ?></a></li>
                        <?php endif; ?>
                    </ul>

                </div>
                <h3 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($_product->getName(), null, true) ?>"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?></a></h3>
                <?php if($_product->getRatingSummary()): ?>
                <?php // echo $this->getReviewsSummaryHtml($_product, 'short') ?>
                <?php endif; ?>
                <?php echo $this->getPriceHtml($_product, true) ?>
                <div class="actions">
                    <?php if($_product->isSaleable()): ?>
                        <?php if ( !($_product->getTypeInstance(true)->hasRequiredOptions($_product) || $_product->isGrouped()) ) { ?>
                            if add<button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocationAjax('<?php echo $this->getAddToCartUrl($_product) ?>','<?php echo $_product->getId()?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
                            <span id='ajax_loader<?php echo $_product->getId()?>' style='display:none'><img src='<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif')?>'/></span>
                        <?php } else { ?>
                            else popup<button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="showOptions('<?php echo $_product->getId()?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
                            <a href='<?php echo $this->getUrl('ajax/index/options',array('product_id'=>$_product->getId()));?>' class='fancybox' id='fancybox<?php echo $_product->getId()?>' style='display:none'>Test</a>
                        <?php }  ?>
                    <?php else: ?>
                        <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
                    <?php endif; ?>

                </div></div>

            </li>
        <?php if ($i%$_columnCount==0 || $i==$_collectionSize): ?>

        <?php endif ?>
        <?php endforeach ?>
        </ul>
        <script type="text/javascript">decorateGeneric($$('ul.products-grid'), ['odd','even','first','last'])</script>
    <?php endif; ?>


    <div class="toolbar-bottom">
        <?php echo $this->getToolbarHtml() ?>
    </div>
</div>
<?php endif; ?>
    <script type="text/javascript">decorateList('products-list', 'none-recursive')</script>
    <script type="text/javascript">
        jQuery(document).ready(function(){
            jQuery('.ajax-fancybox').fancybox(
                {
                   hideOnContentClick : true,
                   width:600,
                   autoDimensions: true,
                   type : 'iframe',
                   showTitle: false,
                   scrolling: 'no',
                   onComplete: function(){
                    jQuery('#fancybox-frame').load(function() { // wait for frame to load and then gets it's height
                        jQuery('#fancybox-content').height(jQuery(this).contents().find('body').height()+30);
                        jQuery.fancybox.resize();
                     });

                   }
                }
            );

            /* Quick Shop buttons */
            function quickViewButton(){
                jQuery('button.btn-quick-view').each(function(){
                    var buttonWidth = jQuery(this).children('span').outerWidth();
                    var imageWidth = jQuery(this).parent().width();
                    jQuery(this).css('margin-left', (imageWidth-buttonWidth)/2);
                });
            }
            quickViewButton();
            jQuery(window).resize(function(){
                quickViewButton();
            });

        });
function showOptions(id){
        jQuery('#fancybox'+id).trigger('click');
    }



    function setAjaxData(data,iframe){
        if(data.status == 'ERROR'){
            alert(data.message);
        }else{
            if(jQuery('.block-cart')){
                jQuery('.block-cart').replaceWith(data.sidebar);
            }
            if(jQuery('#top-info .links')){
                jQuery('#top-info .links').replaceWith(data.toplink);
            }
            jQuery.fancybox.close();
        }
    }
    function setLocationAjax(url,id){

        url += 'isAjax/1';
        url = url.replace("checkout/cart","ajax/index");
        jQuery('#ajax_loader'+id).show();
        try {
            jQuery.ajax( {
                url : url,
                dataType : 'json',
                success : function(data) {
                    jQuery('#ajax_loader'+id).hide();
                    setAjaxData(data,false);          
                }
            });
        } catch (e) {
        }
    }

    </script>
2

I've not had chance to test the code, but I'd guess the issue with not adding products to the basket (i.e. empty cart) is due to Magento 1.8 introducing the FORMKEY element. (see https://stackoverflow.com/questions/19153691/magento-add-a-product-to-the-cart-via-query-string-without-form-key-parameter). Looks like you can get the form key from the session:

Mage::getSingleton('core/session')->getFormKey();

1

Another reason for this would be a cookie configuration problem. Go to System > Configuration > General > Web > Session Cookie Management and set cookie path and cookie domain. I encountered this problem on older magento versions as well, and especially when using IE browsers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.