1 Comment

“Uncaught TypeError: Cannot read property 'submit' of undefined” while adding product to basket

Change block type programmatically from controller

I am working with a mobile theme.
I am trying to make an ajax request to add the product from product detail page and show a pop up after the addition.
But while clicking the “Add to cart” button it shows following error
Uncaught TypeError: Cannot read property 'submit' of undefined

My catalog/product/view.phtml is..

<?php 
 $_helper = $this->helper('catalog/output');
 $_product = $this->getProduct(); 
 $productName = $_helper->productAttribute($_product, $_product->getName(), 'name'); 
 $productUrl = $_helper->productAttribute($_product, $_product->getProductUrl(), 'product_url');
 $productImage = $_product->getImageUrl(); 
?>
<div id="add-product-container" class="jqmWindow" style="display:none">
<ul class="messages clearfix" id="add-product">
    <li class="success-msg" align="center">
        <ul>
            <li align="center">
                <span class="spnPrdname"><?php echo $productName; ?></span>     
            </li>
            <li align="center">
                <span>has been added to <a href="<?php echo $this->getUrl('checkout/cart'); ?>" class="text-link">your basket</a></span>
            </li>
        </ul>
    </li>
</ul>
</div>
<section class="product clearfix" itemscope itemtype="http://schema.org/Product">
<div class="clearfix">
    <div class="product-control">
        <div class="product-images contpdng pdngbtm0">
            <?php echo $this->getChildHtml('media'); ?>
            <?php if ($_product->getPromoImage() != "no_selection" && $_product->getPromoImage()) : ?>
                <?php $imageUrl = $this->helper('catalog/image')->init($_product, 'promo_image');
                if ($this->getMaxWidth() || $this->getMaxHeight())
                {
                        $imageUrl
                                ->keepAspectRatio(true)
                                ->keepFrame(false)
                                ->constrainOnly(true)
                                ->resize($this->getMaxWidth(), $this->getMaxHeight());
                } ?>
            <?php endif; ?>
        </div>
    <div class="page-title singleprdtitle">
        <h1 itemprop="name"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?></h1>
    <?php echo $this->getChildHtml('breadcrumbs'); ?>
    <div style="display: none;">
        <?php echo $this->getPriceHtml($_product) ?>
    </div>
    <?php
    if($_product->getMsrp() && 1==0):

        $difference = $_product->getMsrp() - $_product->getPrice();
        echo '<p class="msrp">You save '.$this->helper('core')->currency($difference, true, true).' <span>(list '.$this->helper('core')->currency($_product->getMsrp(), true, true).' ex VAT)</span></p>';
    endif;
    ?>
</div>
        <div class="product-review div pdnglftrht45">
                <?php echo $this->getReviewsSummaryHtml($_product, 'aggregate', true)?>
        </div>            
    </div>
    <div class="product-info">
        <div class="product-info-row clearfix">
            <div class="pdnglftrht34">
                <div class="product-info-pricing bdrbtm bdrtop pdnglftrht11">
                    <?php echo $this->getChildHtml('product_type_data') ?>
                </div>
            </div>
            <?php echo $this->getChildHtml('alert_urls'); ?>
            <?php    
            $stockItem = $_product->getStockItem();
            if($stockItem->getIsInStock()){ ?>   
                    <?php echo $this->getTierPriceHtml(); ?>
                    <form action="<?php echo $this->getSubmitUrl($_product); ?>" method="post" id="product_addtocart_form" <?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?> class="generic-form">
                        <?php echo $this->getChildHtml('extrahint'); ?>
                        <?php echo $this->getChildHtml('crosssell') ?>
                        <?php echo $this->getChildHtml('other');?>
                        <?php if ($_product->isSaleable() && $this->hasOptions()):?>
                            <?php echo $this->getChildChildHtml('container1', '', true, true) ?>
                        <?php endif;?>

                        <?php if ($_product->isSaleable() && $this->hasOptions()):?>
                        <fieldset>
                            <ol>
                                <?php echo $this->getChildChildHtml('container2', '', true, true) ?>
                            </ol>
                        </fieldset>
                        <?php endif;?>
                        <?php if (!$this->hasOptions()):?>
                            <?php echo $this->getChildHtml('addtocart') ?>
                        <?php endif; ?>
                        <input type="hidden" name="product" value="<?php echo $_product->getId() ?>" />
                        <input type="hidden" name="related_product" id="other-products-field" value="" />
                    </form>
            <?php } else{ ?>    
                <div class="out-of-stock">
                    <p>Out of stock!</p>
                    <p><a class="getintouch" href="javascript:void(0)">Get in touch to pre-order</a></p>
                </div>
            <?php }  ?> 
        </div>
    </div>
</div>
<?php foreach ($this->getChildGroup('detailed_info', 'getChildHtml') as $alias => $html):?>
    <article>
            <?php if ($title = $this->getChildData($alias, 'title')):?>
                <h2><?php echo $this->escapeHtml($title); ?></h2>
            <?php endif;?>
            <?php echo $html; ?>    
    </article>
<?php endforeach;?>

<script type="text/javascript">
    var optionsPrice = new Product.OptionsPrice(<?php echo $this->getJsonConfig() ?>);
</script>
<div id="messages_product_view">
    <?php echo $this->getMessagesBlock()->getGroupedHtml() ?>
</div>
<div class="product-view" itemscope itemtype="http://schema.org/Product">
    <div class="product-essential">
        <script type="text/javascript" src="<?php echo $this->getSkinUrl(); ?>js/jqModal.js"></script>
            <script type="text/javascript"> 
            jQuery.noConflict();
           // jQuery('#add-product-container').jqm({
           //     modal: true
           // });
           jQuery('#add-product-container').jqmAddClose('.close-modal');
            //<![CDATA[
           var productAddToCartForm = new VarienForm('product_addtocart_form');
           productAddToCartForm.submit = function(button, url) {alert("inside submit function");
               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');
                   }
                   url = url.replace("checkout/cart","ajax/index"); // New Code

                   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('.empty')) {
                                   jQuery('.mini-basket').replaceWith(data.sidebar);
                               }
                                   var html_string = data.sidebar.toString();
                                   var item = jQuery(html_string).find( '#mini-basket-product-<?php // echo $_product->getId() ?>' );
                                   jQuery('.mini-basket #mini-basket-product-<?php // echo $_product->getId() ?>').replaceWith(item);
                               }     
                               jQuery('#add-product-container').jqmShow();
                           }
                       });
                   } catch (e) {
                   }
                   this.form.action = oldUrl;
                   if (e) {
                       throw e;
                   }
                   if (button && button != 'undefined') {
                       //button.disabled = true;
                   }
               }
           }.bind(productAddToCartForm);

            productAddToCartForm.submitLight = function(button, url){
                if(this.validator) {
                    var nv = Validation.methods;
                    delete Validation.methods['required-entry'];
                    delete Validation.methods['validate-one-required'];
                    delete Validation.methods['validate-one-required-by-name'];
                    if (this.validator.validate()) {
                        if (url) {
                            this.form.action = url;
                        }
                        this.form.submit();
                    }
                    Object.extend(Validation.methods, nv);
                }
            }.bind(productAddToCartForm);
            //]]>
            </script> 
    </div>
</div>

<?php echo $this->getChildHtml('product_reviews') ?>
<div class="mrgnbtm25"></div>
<?php echo $this->getChildHtml('product_additional_data') ?>

And my catalog/product/view/addtocart.phtml is..

<?php  
  $_product = $this->getProduct(); 
  $_quantity = intval(Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty());
  $buttonTitle = $this->__('Add to Cart'); 
?>
  <?php 
    $stockItem = $_product->getStockItem();
    if($stockItem->getIsInStock()){ ?>
      <?php if($_product->isSaleable()): ?>
        <fieldset class="last-child pdnglftrht45 mrgnbtm58">
            <table width="100%" cellspacing="0" cellpadding="0" class="adtocartTbl font22">
                <tr>
                    <?php if(!$_product->isGrouped()): ?>
                    <td class="tdfirst" valign="middle">
                    <label for="qty" class="lblQty">Quantity: </label>
                    </td>
                    <td class="tdscnd">
                    <select name="qty" id="qty" class="qty">
                        <?php 
                            $counter = 1;
                            while ( $counter<= 100) {
                                echo "<option value=".$counter.">".$counter."</option>";
                                $counter++;
                            }
                        ?>
                    </select>
                    </td>
                    <?php endif; ?>
                    <td class="tdthrd">
                    <input type="submit" value="" class="btn btnAdd2cart btn-checkout" onclick="productAddToCartForm.submit(this)">
                    <p class="in-stock">In stock!</p>
                    <span id='ajax_loader' style='display:none'><img src='<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif')?>'/></span>
                    </td>
                </tr>
            </table>
        </fieldset>
<?php endif; ?>
<?php } else { ?>
<div class="out-of-stock">
    <p>Out of stock!</p>
    <p><a class="getintouch" href="javascript:void(0)">Get in touch to pre-order</a></p>
</div>
<?php }  ?>

I guess it is javascript conflict error. So I extract .js files from view source in the following order.

<script src="project/js/jquery/jquery-1.10.2.min.js"></script>
<script src="project/js/prototype/prototype.js"></script>
<script src="project/js/lib/ccard.js"></script>
<script src="project/js/prototype/validation.js"></script>
<script src="project/js/scriptaculous/builder.js"></script>
<script src="project/js/scriptaculous/effects.js"></script>
<script src="project/js/scriptaculous/dragdrop.js"></script>
<script src="project/js/scriptaculous/controls.js"></script>
<script src="project/js/scriptaculous/slider.js"></script>
<script src="project/js/varien/js.js"></script>
<script src="project/js/varien/form.js"></script>
<script src="project/js/mage/translate.js"></script>
<script src="project/js/mage/cookies.js"></script>
<script src="project/js/varien/product.js"></script>
<script src="project/js/varien/configurable.js"></script>
<script src="project/js/calendar/calendar.js"></script>
<script src="project/js/calendar/calendar-setup.js"></script>
<script src="project/js/jquery/noconflict.js"></script>
<script src="project/skin/frontend/Mystore/iphone/js/jquery-ui.min.js"></script>
<script src="project/skin/frontend/Mystore/iphone/js/modernizr.js"></script>
<script src="project/skin/frontend/Mystore/iphone/js/iphone.js"></script>
<script src="project/skin/frontend/Mystore/iphone/js/dnd.js"></script>
<script src="project/skin/frontend/Mystore/iphone/js/bookmarkscroll.js"></script>
<script src="project/skin/frontend/base/default/js/ajaxwishlist/ajaxwishlist.js"></script>
<script src="project/skin/frontend/base/default/ig_lightbox2/fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<script src="project/skin/frontend/base/default/ig_lightbox2/fancybox/jquery.mousewheel-3.0.4.pack.js"></script>
<script src="project/skin/frontend/base/default/ig_lightbox2/fancybox/jquery.easing-1.3.pack.js"></script>
<script src="project/skin/frontend/Mystore/iphone/js/jqModal.js"></script>

Related Posts

  • Featured Product Slider Not Working Properly (2)
    In my Magneto Mobile homepage. Featured Product Slider Not Working Properly. When i add this code to my mobile_homepage static block it will work only once. when i try to add another category with this code. slider is not working. it will show product big images. Url […]
  • How to show price(including tax) in the basket page? (1)
    In my cart page (i.e checkout/cart.phtml) each added product with price and total product price(subtotal) is shown as following... <div class="cart contpdng"> <form action="<?php echo $this->getUrl('checkout/cart/updatePost') ?>" method="post"> […]
  • M2: Custom form validation (1)
    I have an ajax form I need to call before allowing user to continue to add a product to cart. I have the form popping up but I also need to validate the contents before it submits. However the validation has changed from M1 to M2. Essentially I need to: on form submit validate the […]
  • Capture error message in custom mddule from helper to controller to admin phtml with ajax call 🙂 (2)
    in the process of creating a custom module to learn the magento structure but I am stuck in how to handle errors. Well maybe the way I created my module is already off but it works for now. Only want to add some error feedback. So let me explain. With this tutorial I created my […]
  • Call custom attribute in Listing page (0)
    I have a custom drop down attribute how to call in listing page with link and count if user click which product have same attribute that product only display. I don't want to all filter option i need only one attribute filter under 1column.phtml My code <?php […]
  • Ajax load the category custom product collection on custom phtml? (1)
    I have a phtml file which displays all subcategory with its product.I want to load the products of particular category section using ajax when user select a radio button.Give me some solution. sample code customphtml file. <?php foreach ($categories as $category): ?> […]
  • Bug in adding configurable product to cart pop up (1)
    When I select a product of specific color of a configurable product and add it to cart, In cart pop up Two products are displayed one indicating the color and the other is simply the product name with image. I need to display exactly the selected color product in the cart pop up. […]
  • Removing confirmation prompt from one step checkout (0)
    I have Magestore one step checkout on two store views. I have been using AJAX so not had this problem before but on one of the store views I have AJAX disabled so now when I want to remove an item from the cart it pops up with a dialog box asking "website.com says are you sure? OK […]
  • How to move gallery in a tab? (1)
    I want to have the photo gallery in a tab like some of the other content. I then tried as per below. In my app/design/frontend/Vendor/Theme/Magento_Catalog/layout/catalog_product_view.xml I have the following : <body> <referenceBlock name="product.info.details"> […]
  • How to move gallery in a tab? (1)
    I want to have the photo gallery in a tab like some of the other content. I then tried as per below. In my app/design/frontend/Vendor/Theme/Magento_Catalog/layout/catalog_product_view.xml I have the following : <body> <referenceBlock name="product.info.details"> […]
Change block type programmatically from controller

1 Comment on this article

  • User November 12, 2016

    Just curious…

    Is the full jQuery library included in:

    <script src="project/js/jquery/noconflict.js"></script>
    

    If so – you’re causing a conflict with the existing jQuery being loaded at the top of the includes list you provided. Try removing

    noconflict.js

    Reply

Add a comment

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax