1

I want to provide an option for "entering zip code and finding shipping charges per product inside table of cart page". its not working for 1st & 3rd product. but working for 2nd product.

Here problem is there is no ajax request implemented. two post_code inputbox with same name, same id and same form. When event call submit then it's not identify that which form have to submit. both button id are same. Please help me to create an Ajax request to find shipping charges inside table

ex: visit link1 , link2 , link3 and click on "Buy now Button for all 3 links , you can see "Check Delivery" text, try entering zip code "560043" in 1st and 3rd products. it will not work. but when you try for 2nd product , its working.

enter image description here

shipping1.phtml

<?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 [email protected] 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) 2014 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<?php /** @var $this Mage_Checkout_Block_Cart_Shipping */ ?>
<div class="shipping">
    <h2><?php echo $this->__('') ?></h2>
    <div class="shipping-form">
       <form action="<?php echo $this->getUrl('checkout/cart/estimatePost') ?>" method="post" id="shipping-zip-form">

            <ul class="form-list">
            <div style="display:none">

               <li>
                    <label for="country"><em>*</em><?php echo $this->__('Country') ?></label>
                <div class="input-box">
                        <?php echo Mage::getBlockSingleton('directory/data')->getCountryHtmlSelect($this->getEstimateCountryId()) ?>
                    </div>

                </li>
            </div>

            <?php //if($this->getStateActive()): ?>
            <!--
                <li>
                    <label for="region_id"<?php if ($this->isStateProvinceRequired()) echo ' class="required"' ?>><?php if ($this->isStateProvinceRequired()) echo '<em>*</em>' ?><?php echo $this->__('State/Province') ?></label>
                    <div class="input-box">
                        <select id="region_id" name="region_id" title="<?php echo $this->__('State/Province') ?>" style="display:none;"<?php echo ($this->isStateProvinceRequired() ? ' class="validate-select"' : '') ?>>
                            <option value=""><?php echo $this->__('Please select region, state or province') ?></option>
                        </select>
                       <script type="text/javascript">
                       //<![CDATA[
                           $('region_id').setAttribute('defaultValue',  "<?php echo $this->getEstimateRegionId() ?>");
                       //]]>
                       </script>
                       <input type="text" id="region" name="region" value="<?php echo $this->escapeHtml($this->getEstimateRegion()) ?>"  title="<?php echo $this->__('State/Province') ?>" class="input-text" style="display:none;" />
                   </div>
                </li>
            -->
            <?php //endif; ?>
            <?php if($this->getCityActive()): ?>
                <li>
                    <label for="city"<?php if ($this->isCityRequired()) echo ' class="required"' ?>><?php if ($this->isCityRequired()) echo '<em>*</em>' ?><?php echo $this->__('City') ?></label>
                    <div class="input-box">
                        <input class="input-text<?php if ($this->isCityRequired()):?> required-entry<?php endif;?>" id="city" type="text" name="estimate_city" value="<?php echo $this->escapeHtml($this->getEstimateCity()) ?>" />
                    </div>
                </li>
            <?php endif; ?>
                <li>
                    <label for="postcode"<?php if ($this->isZipCodeRequired()) echo ' class="required"' ?>><?php if ($this->isZipCodeRequired()) echo '<em>*</em>' ?><?php echo $this->__('Check Delivery') ?></label>
                    <div class="input-box">
                        <input class="input-text validate-postcode<?php if ($this->isZipCodeRequired()):?> required-entry<?php endif;?>" type="text" id="postcode1" name="estimate_postcode" value="<?php echo $this->escapeHtml($this->getEstimatePostcode()) ?>" />
                    </div>
                </li>
            </ul>
            <div class="buttons-set">
                 <button type="button" title="<?php echo $this->__('Check') ?>" onclick="getshippingcost();" class="button">
                 <span><span><?php echo $this->__('Check') ?>
                 </span></span></button>
            </div>

        </form>

        <!-- Pras -->
     <td>


    <?php if (($_shippingRateGroups = $this->getEstimateRates())):

     if(Mage::getSingleton('core/session')->getMyShipMessage()){
             echo Mage::getSingleton('core/session')->getMyShipMessage();
             Mage::getSingleton('core/session')->unsMyShipMessage();
        }

    endif; ?>   
    </td>   

    <!-- Pras end -->


        <script type="text/javascript">
        //<![CDATA[
            new RegionUpdater('country', 'region', 'region_id', <?php echo $this->helper('directory')->getRegionJson() ?>);
        //]]>
        </script>



        <?php if (($_shippingRateGroups = $this->getEstimateRates())): ?>
        <form id="co-shipping-method-form" action="<?php echo $this->getUrl('checkout/cart/estimateUpdatePost') ?>">
            <dl class="sp-methods">
                <?php foreach ($_shippingRateGroups as $code => $_rates): ?>
                    <dt><?php echo $this->escapeHtml($this->getCarrierName($code)) ?></dt>
                    <dd>
                        <ul>
                        <?php foreach ($_rates as $_rate): ?>
                            <li<?php if ($_rate->getErrorMessage()) echo ' class="error-msg"';?>>
                               <?php if ($_rate->getErrorMessage()): ?>
                                    <?php echo $this->escapeHtml($_rate->getErrorMessage()) ?>
                               <?php else: ?>
                                    <input name="estimate_method" type="radio" value="<?php echo $this->escapeHtml($_rate->getCode()) ?>" id="s_method_<?php echo $_rate->getCode() ?>"<?php if($_rate->getCode()===$this->getAddressShippingMethod()) echo ' checked="checked"' ?> class="radio" />
                                    <label for="s_method_<?php echo $_rate->getCode() ?>"><?php echo $this->escapeHtml($_rate->getMethodTitle()) ?>
                                    <?php $_excl = $this->getShippingPrice($_rate->getPrice(), $this->helper('tax')->displayShippingPriceIncludingTax()); ?>
                                    <?php $_incl = $this->getShippingPrice($_rate->getPrice(), true); ?>
                                    <?php echo $_excl; ?>
                                    <?php if ($this->helper('tax')->displayShippingBothPrices() && $_incl != $_excl): ?>
                                        (<?php echo $this->__('Incl. Tax'); ?> <?php echo $_incl; ?>)
                                    <?php endif; ?>
                                    </label>
                               <?php endif ?>
                            </li>
                        <?php endforeach; ?>
                        </ul>
                    </dd>
                <?php endforeach; ?>
            </dl>
            <div style="display:none;">
                <button type="submit" title="<?php echo $this->__('Update Total') ?>" class="button" name="do" 
                value="<?php echo $this->__('Update Total') ?>"><span><span><?php echo $this->__('Update Total') ?></span></span>
                </button>
            </div>
        </form>
        <?php endif; ?>
        <script type="text/javascript">
        //<![CDATA[
            var coShippingMethodForm = new VarienForm('shipping-zip-form');
            var countriesWithOptionalZip = <?php echo $this->helper('directory')->getCountriesWithOptionalZip(true) ?>;

            function getshippingcost()
            {
                //alert(document.getElementById('postcode1').value);
                document.getElementById('postcode').value=document.getElementById('postcode1').value;
                var country = $F('country');
                var optionalZip = false;

                for (i=0; i < countriesWithOptionalZip.length; i++) {
                    if (countriesWithOptionalZip[i] == country) {
                        optionalZip = true;
                    }
                }
                if (optionalZip) {
                    $('postcode').removeClassName('required-entry');
                }
                else {
                    $('postcode').addClassName('required-entry');
                }
                return VarienForm.prototype.submit.bind(coShippingMethodForm)();
            }   

        //]]>   

        </script

    </div>
</div>

3 Answers 3

1

I've entered 560043 and clicked check button. Problem is the data is not being sent to the server estimate_postcode in the post is empty. Please check the screen cast here. If you fix, then this should be start working, since you are just replicating the estimatePostAction. You can also try the same in Ajax which would be much more user friendly. Here is the code

  1. Remove this coShippingMethodForm.submit() from the click action on the button.

  2. set an id for the button as delivery_button

  3. then copy this code in the same phtml where you have made above changes. jQuery(document).ready(function(){ jQuery("#delivery_button").click(function(){ jQuery.ajax({ method:'post', data:jQuery('form#scart').serialize(), url:'<?php echo $this->getUrl('checkout/cart/estimatePost/', array('_secure'=>true)) ?>', dataType:'json', success:function(result,status,xhr){alert(result);//print the message in a div or span}, error: function(r,e){console.log(r.responseText);} }); } }

  4. override estimatePostAction function present in cartController.php and add
    if($this->getRequest()->isXmlHttpRequest()) { //Print the json message here }else{ $this->_goBack() }
    instead of $this->_goBack().

this way you are making the function to respond properly for ajax and non ajax requests.

7
  • can you please give the ajax code to fix this problem
    – user33510
    Commented Mar 11, 2016 at 6:34
  • I have updated the answer with the jQuery ajax code. Let me know if you need further details. Commented Mar 11, 2016 at 7:22
  • i added script in default.phtml and in shipping.phtml , but it didt worked for me
    – user33510
    Commented Mar 11, 2016 at 7:41
  • did i added the code in correct file ?
    – user33510
    Commented Mar 11, 2016 at 7:49
  • when i add the code, "check" button stopped working.
    – user33510
    Commented Mar 11, 2016 at 7:51
2

Its working for me. click here

and for shipping charge you need to create table-rate.

9
  • yes, it will work for finding Delivery is available or not. but it will not help to find shipping charges based on zip code.
    – user33510
    Commented Mar 14, 2016 at 11:29
  • yes for this you need to use table rate method for shipping charges. you just setup zipcode and shipping prices.
    – Ajay Patel
    Commented Mar 14, 2016 at 11:34
  • for some features, i need to use custom shipping method. will this extension for work for custom shipping method also, or is there any way to achieve this ?
    – user33510
    Commented Mar 14, 2016 at 11:36
  • yes, you can use with this, just you need to add all delivery support zip code in back end field.
    – Ajay Patel
    Commented Mar 14, 2016 at 11:41
  • 1
    ok. its ok. NOP. :)
    – Ajay Patel
    Commented Mar 14, 2016 at 11:50
1
+50

Try this in cartcontroller.php

public function estimatePost1Action($productId)
    {
$zipcode   = (string) $this->getRequest()->getParam('zipcode');

        // Update the cart's quote.
        $cart = Mage::getSingleton('checkout/cart');
        $address = $cart->getQuote()->getShippingAddress();
        $address->setPostcode($zipcode)
                ->setCollectShippingrates(true);
        //$cart->save();

        // Find if our shipping has been included.
        $rates = $address->collectShippingRates()
                         ->getGroupedAllShippingRates();
        $count=1;
        foreach ($rates as $carrier) {
        foreach ($carrier as $rate) {     

               $count=$count+1;
                $rate=$rate->getPrice();
                $i++;
            }
        }

        echo (int) $rate/$count;


        die;
}

use this code in Default.phtml

<?php 
echo $this->getLayout()->createBlock('checkout/cart_shipping')->setProductId($pId)->setTemplate('checkout/cart/shipping1.phtml')->tohtml(); 
?>

shipping1.phtml

<?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 [email protected] 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) 2014 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<?php /** @var $this Mage_Checkout_Block_Cart_Shipping */ ?>
<?php $pId=$this->getProductId();?>
<div class="shipping">
    <h2><?php echo $this->__('') ?></h2>
    <div class="shipping-form">
       <form action="<?php echo $this->getUrl('checkout/cart/estimatePost') ?>" method="post" id="shipping-zip-form">

            <ul class="form-list">
            <div style="display:none">

               <li>
                    <label for="country"><em>*</em><?php echo $this->__('Country') ?></label>
                <div class="input-box">
                        <?php echo Mage::getBlockSingleton('directory/data')->getCountryHtmlSelect($this->getEstimateCountryId()) ?>
                    </div>

                </li>
            </div>

            <?php //if($this->getStateActive()): ?>
            <!--
                <li>
                    <label for="region_id"<?php if ($this->isStateProvinceRequired()) echo ' class="required"' ?>><?php if ($this->isStateProvinceRequired()) echo '<em>*</em>' ?><?php echo $this->__('State/Province') ?></label>
                    <div class="input-box">
                        <select id="region_id" name="region_id" title="<?php echo $this->__('State/Province') ?>" style="display:none;"<?php echo ($this->isStateProvinceRequired() ? ' class="validate-select"' : '') ?>>
                            <option value=""><?php echo $this->__('Please select region, state or province') ?></option>
                        </select>
                       <script type="text/javascript">
                       //<![CDATA[
                           $('region_id').setAttribute('defaultValue',  "<?php echo $this->getEstimateRegionId() ?>");
                       //]]>
                       </script>
                       <input type="text" id="region" name="region" value="<?php echo $this->escapeHtml($this->getEstimateRegion()) ?>"  title="<?php echo $this->__('State/Province') ?>" class="input-text" style="display:none;" />
                   </div>
                </li>
            -->
            <?php //endif; ?>
            <?php if($this->getCityActive()): ?>
                <li>
                    <label for="city"<?php if ($this->isCityRequired()) echo ' class="required"' ?>><?php if ($this->isCityRequired()) echo '<em>*</em>' ?><?php echo $this->__('City') ?></label>
                    <div class="input-box">
                        <input class="input-text<?php if ($this->isCityRequired()):?> required-entry<?php endif;?>" id="city" type="text" name="estimate_city" value="<?php echo $this->escapeHtml($this->getEstimateCity()) ?>" />
                    </div>
                </li>
            <?php endif; ?>
                <li>
                    <label for="postcode"<?php if ($this->isZipCodeRequired()) echo ' class="required"' ?>><?php if ($this->isZipCodeRequired()) echo '<em>*</em>' ?><?php echo $this->__('Check Delivery') ?></label>
                    <div class="input-box">
                        <input class="input-text validate-postcode<?php if ($this->isZipCodeRequired()):?> required-entry<?php endif;?>" type="text" id="postcode<?php echo $pId?>" name="estimate_postcode" value="<?php echo $this->escapeHtml($this->getEstimatePostcode()) ?>" />
                    </div>
                    <span id="costmsg<?php echo $pId?>"></span>
                </li>
            </ul>
            <div class="buttons-set">
                 <button type="button" title="<?php echo $this->__('Check') ?>" id="delivery_button" onclick="checkshipping('<?php echo $pId?>')" class="button">
                 <span><span><?php echo $this->__('Check') ?>
                 </span></span></button>
            </div>

        </form>

        <!-- Pras -->
     <td>


    <?php if (($_shippingRateGroups = $this->getEstimateRates())): 

     if(Mage::getSingleton('core/session')->getMyShipMessage()){
             echo Mage::getSingleton('core/session')->getMyShipMessage();
             Mage::getSingleton('core/session')->unsMyShipMessage();
        }

    endif; ?>   
    </td>   

    <!-- Pras end -->


        <script type="text/javascript">
        //<![CDATA[
            new RegionUpdater('country', 'region', 'region_id', <?php echo $this->helper('directory')->getRegionJson() ?>);
        //]]>
        </script>
        <?php if (($_shippingRateGroups = $this->getEstimateRates())): ?>
        <form id="co-shipping-method-form" action="<?php echo $this->getUrl('checkout/cart/estimateUpdatePost') ?>">
            <dl class="sp-methods11">
                <?php foreach ($_shippingRateGroups as $code => $_rates): ?>
                    <dt><?php echo $this->escapeHtml($this->getCarrierName($code)) ?></dt>
                    <dd>
                        <ul>
                        <?php foreach ($_rates as $_rate): ?>
                            <li<?php if ($_rate->getErrorMessage()) echo ' class="error-msg"';?>>
                               <?php if ($_rate->getErrorMessage()): ?>
                                    <?php echo $this->escapeHtml($_rate->getErrorMessage()) ?>
                               <?php else: ?>
                                    <input name="estimate_method" type="radio" value="<?php echo $this->escapeHtml($_rate->getCode()) ?>" id="s_method_<?php echo $_rate->getCode() ?>"<?php if($_rate->getCode()===$this->getAddressShippingMethod()) echo ' checked="checked"' ?> class="radio" />
                                    <label for="s_method_<?php echo $_rate->getCode() ?>"><?php echo $this->escapeHtml($_rate->getMethodTitle()) ?>
                                    <?php $_excl = $this->getShippingPrice($_rate->getPrice(), $this->helper('tax')->displayShippingPriceIncludingTax()); ?>
                                    <?php $_incl = $this->getShippingPrice($_rate->getPrice(), true); ?>
                                    <?php echo $_excl; ?>
                                    <?php if ($this->helper('tax')->displayShippingBothPrices() && $_incl != $_excl): ?>
                                        (<?php echo $this->__('Incl. Tax'); ?> <?php echo $_incl; ?>)
                                    <?php endif; ?>
                                    </label>
                               <?php endif ?>
                            </li>
                        <?php endforeach; ?>
                        </ul>
                    </dd>
                <?php endforeach; ?>
            </dl>
            <div style="display:none;">
                <button type="submit" title="<?php echo $this->__('Update Total') ?>" class="button" name="do" 
                value="<?php echo $this->__('Update Total') ?>"><span><span><?php echo $this->__('Update Total') ?></span></span>
                </button>
            </div>
        </form>
        <?php endif; ?>

        <script type="text/javascript">
        //<![CDATA[

function checkshipping(pid){

    var zip=jQuery("#postcode"+pid).val();
    jQuery.ajax({
        method:'post',
        data: { 'zipcode': zip} ,
        url:'<?php echo $this->getUrl('checkout/cart/estimatePost1/', array('_secure'=>true)) ?>',
        dataType:'json',
        success:function(result,status,xhr){alert(result);
          //  jQuery("#costmsg"+pid).html('MP Per Product Shipping '+result);
            document.getElementById('costmsg'+pid).innerHTML='MP Per Product Shipping '+result;
        //print the message in a div or span
    },
        error: function(r,e){console.log(r.responseText);}
    });
}

            var coShippingMethodForm = new VarienForm('shipping-zip-form');
            var countriesWithOptionalZip = <?php echo $this->helper('directory')->getCountriesWithOptionalZip(true) ?>;

            coShippingMethodForm.submit = function () {
                var country = $F('country');
                var optionalZip = false;

                for (i=0; i < countriesWithOptionalZip.length; i++) {
                    if (countriesWithOptionalZip[i] == country) {
                        optionalZip = true;
                    }
                }
                if (optionalZip) {
                    $('postcode').removeClassName('required-entry');
                }
                else {
                    $('postcode').addClassName('required-entry');
                }
                return VarienForm.prototype.submit.bind(coShippingMethodForm)();
            }   

        //]]>


        </script>





    </div>
</div>

After that you have to update quote_item table for shipping cost. Hope it's help you.

1
  • Now its working for only one product, but its giving half of the total shipping charges for one product. how to update "quote_item" table ?
    – user33510
    Commented Mar 18, 2016 at 6:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.