1

I'm working on a mobile design for a Megento product page, what I'm basically doing is duplicating the HTML for desktop and mobile display and showing/hiding the correct design according to the screen size via CSS

My issue is that the AJAX add to cart function does not work because there is more than one add to cart form in the pages HTML, how can I fix this?

Here's my code so far:

<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    design
 * @package     base_default
 * @copyright   Copyright (c) 2013 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

/**
 * Product view template
 *
 * @see Mage_Catalog_Block_Product_View
 * @see Mage_Review_Block_Product_View
 */
?> 
<?php /* Get Current Product's Category */?>
<?php $cat_id = Mage::getModel('catalog/layer')->getCurrentCategory()->getId(); ?>
<?php $_category = Mage::getModel('catalog/category')->load($cat_id); ?>
<?php /* End */?>

<?php $_helper = $this->helper('catalog/output'); ?>
<?php $_product = $this->getProduct(); ?>
<?php $_prev = $_helper->getPreviousProduct(); ?>
<?php $_next = $_helper->getNextProduct(); ?>
<script type="text/javascript">
    var optionsPrice = new Product.OptionsPrice(<?php echo $this->getJsonConfig() ?>);
</script>

<div class="mobile-only visible-xs-block">
<section id="singleProdSection">
<div class="sngleProdContainer">

    <h1 class="prodName"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?></h1>
    <div class="prodSku"><?php echo 'SKU# '.$_product->getSku();?></div>
    <div class="prodImageContainer regBox">
    <img src="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'catalog/product' . $_product->getImage(); ?>" class="prodImg">
    </div><!-- prodImageContainer -->
<form action="<?php echo $this->getSubmitUrl($_product) ?>" method="post" id="product_addtocart_form"<?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>     
    <div class="prodActionContainer regBox">
        <div class="prodActionTop">
            <div class="prodReviews">
                <?php echo $this->getReviewsSummaryHtml($_product, false, true)?>
            </div><!-- prodReviews -->
            <div class="priceContainer">
                <?php echo $this->getChildHtml('product_type_data') ?>
            </div>

            <?php if (!$this->hasOptions()):?>

                    <?php if($_product->isSaleable()): ?>
                        <div class="add-to-cart">
                        <?php //echo $this->getChildHtml('addtocart') ?>
                        <?php $buttonTitle = $this->__('Add to Cart'); ?>
                        <div class="add-to-cart">
                            <?php if(!$_product->isGrouped()): ?>

            <div class="quantityContainer">
                <div class="quantitySet">   

                           <div value="-" id="minus1" class="minus1 dec quantityButton">-</div>

                <input type="text"  name="qty" value="<?php if($this->getProductDefaultQty() == 0){echo 1;}else{ echo getProductDefaultQty() * 1; } ?>" id="qty" class="qty quantityNumber" /> 

                            <div value="+" id="add1" class="add1 inc quantityButton">+</div>




                </div><!-- quantitySet -->
            </div><!-- quantityContainer -->

                        </div>


            </div>
        </div><!-- prodActionTop -->







                        <?php endif; ?>


                        <div class="prodActionBottom">

                           <button type="button" title="<?php echo $buttonTitle ?>" class="addToCart" onclick="productAddToCartForm.submit(this)"><span><span><?php echo $buttonTitle ?></span></span></button>
                        </div><!-- prodActionBottom -->

                        <span id='ajax_loader' style='display:none'><img src='<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif')?>'/></span>

                    <?php endif; ?>

                    <?php ///echo $this->getChildHtml('addto') ?>

                <?php echo $this->getChildHtml('extra_buttons') ?>

            <?php elseif (!$_product->isSaleable()): ?>

                    <?php //echo $this->getChildHtml('addto') ?>

            <?php endif; ?>



        <?php echo $this->getBlockHtml('formkey') ?>
        <div class="no-display">
            <input type="hidden" name="product" value="<?php echo $_product->getId() ?>" />
            <input type="hidden" name="related_product" id="related-products-field" value="" />
        </div> 
        <span id='ajax_loader' style='display:none'><img src='<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif')?>'/></span>
        <?php echo $this->getChildHtml('alert_urls') ?>



            <?php echo $this->getChildHtml('other');?>
            <?php if ($_product->isSaleable() && $this->hasOptions()):?>
                <?php echo $this->getChildChildHtml('container1', '', true, true) ?>
                <!--<div class="freeshipping">Free Shipping</div> -->
                <?php echo $this->getChildHtml('product_type_data') ?>
                <div class="add-to-cart-btn">   
                   <button type="button" title="<?php echo $this->__('Add to Cart'); ?>" class="button btn-cart" onclick="productAddToCartForm.submit(this)"><span><span><?php echo $this->__('Add to Cart'); ?></span></span></button>

                    <?php //echo $this->getChildHtml('', true, true) ?>
                </div>
            <?php endif;?>
            <?php if ($_product->isSaleable() && $this->hasOptions()):?>
                <?php echo $this->getChildChildHtml('container2', '', true, true) ?>
            <?php endif;?>


        <div class="product-collateral toggle-content tabs">
            <?php if ($detailedInfoGroup = $this->getChildGroup('detailed_info', 'getChildHtml')):?>
                <dl id="collateral-tabs" class="collateral-tabs">
                    <?php foreach ($detailedInfoGroup as $alias => $html):?>
                        <dt class="tab"><span><?php echo $this->escapeHtml($this->getChildData($alias, 'title')) ?></span></dt>
                        <dd class="tab-container">
                            <div class="tab-content"><?php echo $html ?></div>
                        </dd>
                    <?php endforeach;?>
                </dl>
            <?php endif; ?>
        </div>
    </div><!-- prodActionContainer -->
</form>

</div><!-- sngleProdContainer -->

</section><!-- singleProdSection -->
</div>

<div class="container">
<div id="messages_product_view"><?php echo $this->getMessagesBlock()->getGroupedHtml() ?></div>
    <div class="custom-popup-cls">
        <div id="allin-custom-messages"  class="ajaxcustommessage" style="display:none">
            <div onclick="closeMeaasePopup()" class="allin">X</div>
            <div id="allin-pid">
                <img src="<?php echo Mage::getModel('catalog/product_media_config')->getMediaUrl($image); ?>" />
            </div>
            <div id="allin-custom-message" class="custom-des-cls">       
                <b style="padding:20px 50px"></b>
            </div>
            <div class="product-information-inpopup">
                <a class="shopping-cls" onclick="closeMeaasePopup()" href="javascript:void(0);<?php //echo Mage::getBaseUrl();?>"><?php echo $this->__('continue shopping')?></a>
                    <span><?php echo $this->__('OR');?></span>
                <a class="checkout-cls" href="<?php echo Mage::getUrl('checkout/cart');?>"><?php echo $this->__('View Cart & Checkout')?></a>
            </div>
        </div>
    </div>
<div class="product-view desktop-olny hidden-xs">
    <!--div id="allin-custom-messages" style="display:none">
        <div onclick="closeMeaasePopup()" class="allin">X</div>
            <div id="allin-custom-message">
            <img src="<?php //echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(300,250); ?>" />

         <b style="padding:20px 50px"></b>
        </div>
    </div-->

    <!--div class="breadcrumb">
        <span>Categories <span>/</span><?php //echo $_category->getName(); ?></span>
    </div-->
    <div class="prod-left">
    <div class="product-essential">
    <form action="<?php echo $this->getSubmitUrl($_product) ?>" method="post" id="product_addtocart_form"<?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
        <?php echo $this->getBlockHtml('formkey') ?>
        <div class="no-display">
            <input type="hidden" name="product" value="<?php echo $_product->getId() ?>" />
            <input type="hidden" name="related_product" id="related-products-field" value="" />
        </div> 
        <div class="col-sm-8 product-image">
            <div class="product-img-box">  
                <!--a href="<?php //echo Mage::getSingleton('core/session')->getLastUrl(); ?>" ><b> << Back </b></a--> 
                <?php echo $this->getChildHtml('media') ?>  
            </div> 
        </div> 
        <span id='ajax_loader' style='display:none'><img src='<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif')?>'/></span>    
       <div class="col-sm-4 product-dis">
       <div class="product-shop">
          <div class="product-name-box"> 

            <div class="product-name">
                <h1><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?></h1>
                <?php /* Products Navigation ?>
                <?php if($_prev): ?><a class="product-prev" href="<?php echo $_prev;?>"><?php echo $this->__('< Previous in '.$_category->getName())?></a><?php endif; ?>
                <?php if($_next): ?><a class="product-next" href="<?php echo $_next;?>"><?php echo $this->__('Next in '.$_category->getName().' >')?></a><?php endif; ?>
                <?php  Products Navigation */?>
            </div>
            <div class="p-sku">
                <?php echo 'SKU# '.$_product->getSku();?>
            </div>
          </div>    
            <?php echo $this->getReviewsSummaryHtml($_product, false, true)?>

            <?php if ($_product->getShortDescription()):?>
                <div class="short-description">
                    <h3>Details</h3>
                    <?php echo $_helper->productAttribute($_product, nl2br($_product->getShortDescription()), 'short_description') ?>

                </div>
            <?php endif;?>



            <?php echo $this->getChildHtml('alert_urls') ?>
            <?php ///echo $this->getTierPriceHtml() ?>
            <?php //echo $this->getChildHtml('extrahint') ?>

            <?php if (!$this->hasOptions()):?>

                    <?php if($_product->isSaleable()): ?>
                        <div class="add-to-cart">
                        <?php //echo $this->getChildHtml('addtocart') ?>
                        <?php $buttonTitle = $this->__('Add to Cart'); ?>
                        <div class="add-to-cart">
                            <?php if(!$_product->isGrouped()): ?>
                            <label for="qty" class="quantity"><?php echo $this->__('Quantity:') ?></label>

                             <input type="button" value="+" id="add1" class="add1 inc" />

                           <input type="button" value="-" id="minus1" class="minus1 dec"/>
                           <input type="text"  name="qty" value="<?php if($this->getProductDefaultQty() == 0){echo 1;}else{ echo getProductDefaultQty() * 1; } ?>" id="qty" class="qty" /> 



                        </div>
                        <?php endif; ?>
                        <?php echo $this->getChildHtml('product_type_data') ?>
                        <div class="add-to-cart-btn">   
                           <button type="button" title="<?php echo $buttonTitle ?>" class="button btn-cart" onclick="productAddToCartForm.submit(this)"><span><span><?php echo $buttonTitle ?></span></span></button>

                            <?php //echo $this->getChildHtml('', true, true) ?>
                        </div>

                        <span id='ajax_loader' style='display:none'><img src='<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif')?>'/></span>

                        </div>
                    <?php endif; ?>

                    <?php ///echo $this->getChildHtml('addto') ?>

                <?php echo $this->getChildHtml('extra_buttons') ?>

            <?php elseif (!$_product->isSaleable()): ?>

                    <?php //echo $this->getChildHtml('addto') ?>

            <?php endif; ?>


            <?php echo $this->getChildHtml('other');?>

            <?php if ($_product->isSaleable() && $this->hasOptions()):?>
                <?php echo $this->getChildChildHtml('container1', '', true, true) ?>
                <!--<div class="freeshipping">Free Shipping</div> -->
                <?php echo $this->getChildHtml('product_type_data') ?>
                <div class="add-to-cart-btn">   
                   <button type="button" title="<?php echo $this->__('Add to Cart'); ?>" class="button btn-cart" onclick="productAddToCartForm.submit(this)"><span><span><?php echo $this->__('Add to Cart'); ?></span></span></button>

                    <?php //echo $this->getChildHtml('', true, true) ?>
                </div>
            <?php endif;?>

        </div>
        </div>

        <div class="clearer"></div>
        <?php if ($_product->isSaleable() && $this->hasOptions()):?>
            <?php echo $this->getChildChildHtml('container2', '', true, true) ?>
        <?php endif;?>

    </form>

    <script type="text/javascript">
    //<![CDATA[
        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;
                try {
                    this.form.submit();
                } catch (e) {
                }
                this.form.action = oldUrl;
                if (e) {
                    throw e;
                }

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

            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();
                                            var curUrl = '<?php echo $currentUrl = Mage::helper('core/url')->getCurrentUrl() ?>';
                                            jQuery('.cart-mini').load(curUrl+" #cart-mini-qty-is");
                                            jQuery('#super-product-table').load(curUrl+" #super-product-table");
                                            jQuery('#header-cart').html(data.minicart);
                                            jQuery('.count').html(data.qty);
                                            jQuery('#allin-custom-message').text(data.message);
                                            jQuery('#allin-custom-messages').show();                     
                                             jQuery('body').append('<div class="color-overlay"></div>');
                                            //alert(data.status + ": " + data.message);
                                            //alert(data.message);
                                      },
                                      complete: function(){
                                      setTimeout(function() {
                                                closeMeaasePopup()
                                           }, 15000);
                                      }
                                });

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

    //]]>

    function closeMeaasePopup(){
            jQuery('#allin-custom-messages').hide();
            jQuery('.color-overlay').hide();
        }
    </script>
    <script type="text/javascript"> 
    jQuery('.reviewtablink').click(function(){
        //alert('asd');
            jQuery('.toggle-tabs li').each(function(obj){
                jQuery(this).removeClass('current');
                if(jQuery(this).hasClass('last')) {
                    jQuery(this).addClass('current'); 
                    } 
                    });
                    jQuery('.collateral-tabs .tab , .collateral-tabs .tab-container').each(function(obj){
                        jQuery(this).removeClass('current');
                        if(jQuery(this).hasClass('last')) {
                            jQuery(this).addClass('current'); 
                            } 
                        });
                        var scrollOffset = 100;
                        var body = jQuery('html, body'); 
                        body.animate({ scrollTop: jQuery('.product-collateral').offset().top-scrollOffset }, 1000); }); 
    </script>
    </div>
        <div class="product-collateral toggle-content tabs">
            <?php if ($detailedInfoGroup = $this->getChildGroup('detailed_info', 'getChildHtml')):?>
                <dl id="collateral-tabs" class="collateral-tabs">
                    <?php foreach ($detailedInfoGroup as $alias => $html):?>
                        <dt class="tab"><span><?php echo $this->escapeHtml($this->getChildData($alias, 'title')) ?></span></dt>
                        <dd class="tab-container">
                            <div class="tab-content"><?php echo $html ?></div>
                        </dd>
                    <?php endforeach;?>
                </dl>
            <?php endif; ?>
        </div>
    </div>

</div>

<div>
    <?php echo $this->getBlockHtml('catalog.product.related'); ?>
</div>


</div>
<script>

jQuery(document).ready(function(){

    var val = jQuery(".qty").val();


    jQuery('.add1').click(function(){

        currentVal = parseInt(jQuery('.qty').val());

         if (parseFloat(currentVal) >= 1 ){



        var plus = currentVal+1;

       }



          jQuery('.qty').val(plus);

    });

    jQuery('.minus1').click(function(){

                  newVal = parseInt(jQuery('.qty').val());

                   if (parseFloat(newVal) >= 2 ){

                  var minus = newVal-1;

                  jQuery('.qty').val(minus);

                  }





    });


});

</script>

As you can see the form gets submitted via onclick="productAddToCartForm.submit(this)" in the button HTML and AJAX is fired using the code below

//<![CDATA[
    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;
            try {
                this.form.submit();
            } catch (e) {
            }
            this.form.action = oldUrl;
            if (e) {
                throw e;
            }

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

        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();
                                        var curUrl = '<?php echo $currentUrl = Mage::helper('core/url')->getCurrentUrl() ?>';
                                        jQuery('.cart-mini').load(curUrl+" #cart-mini-qty-is");
                                        jQuery('#super-product-table').load(curUrl+" #super-product-table");
                                        jQuery('#header-cart').html(data.minicart);
                                        jQuery('.count').html(data.qty);
                                        jQuery('#allin-custom-message').text(data.message);
                                        jQuery('#allin-custom-messages').show();                     
                                         jQuery('body').append('<div class="color-overlay"></div>');
                                        //alert(data.status + ": " + data.message);
                                        //alert(data.message);
                                  },
                                  complete: function(){
                                  setTimeout(function() {
                                            closeMeaasePopup()
                                       }, 15000);
                                  }
                            });

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

//]]>

Thanks in advance!
Martin

  • What I ended up doing is duplicating the entire script separately for the mobile version – martin schwartz Oct 26 '17 at 16:35

Your Answer

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

Browse other questions tagged or ask your own question.