Reading list Switch to dark mode

    How to get estimate shipping rates in magento2 using js

    Updated 22 March 2024

    Here, I am going to explain that how to get estimate shipping using js. Sometimes  we want to display shipping method and rates to customer at product page or another page except to checkout page.

    As we all know that in magento2 use js is more than to php for fast execution and change details when change in data.

    In this blog I will call estimate shipping rates at product view page. You have to add following files to get this functionality : –

    1- Create catalog_product_view.xml file at app/code/Test/Module/view/frontend/layout path. Using this file call block at product view page.

    <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="checkout" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceBlock name="content">
                 <block class="\Magento\Framework\View\Element\Template" name="estimaterate.js" template="Test_Module::estimaterate.phtml" cacheable="false" />
            </referenceBlock>
        </body>
    </page>

    2- Create template file which is define in layout file.app/code/Test/Module/view/frontend/templates/estimaterate.phtml

    Searching for an experienced
    Magento 2 Company ?
    Find out More
    <button id="getrate">Click to get Shipping rate</button>
    <script type="text/x-magento-init">
        {
            "*": {
                "estimateRate":  {}
            }
        }
    </script>

    In this file add only single button. On click of this button send to request for estimate shipping calculation. And also call js file.

    3 – Create app/code/Test/Module/view/frontend/requirejs-config.js

    var config = {
        map: {
            '*': {
                estimateRate : 'Test_Module/js/estimaterate',
            }
        }
    };

    4 – Create app/code/Test/Module/view/frontend/web/js/estimaterate.js .

    In this file call rest/default/V1/carts/mine/estimate-shipping-methods this web api which is define magento default.Using this we can get estimate rate for only login customer.

    If you want to calculate estimate shipping for guest then you have to call rest/default/V1/guest-carts/:quoteId/estimate-shipping-methods and provide cart id in parameters.

    You can check this file for reference vendor/magento/module-checkout/view/frontend/web/js/model/resource-url-manager.js

    define([
        "jquery",
        'mage/storage',
        'Magento_Checkout/js/model/error-processor'
    ], function ($,storage, errorProcessor) {
        'use strict';
        $.widget('mage.estimateRate', {
            options: {
            },
            _create: function () {
                var self = this;
                $(document).ready(function () {
                    $('#product-addtocart-button').after($('#getrate'));
                });
                $('#getrate').on('click', function (e) {
                    var address;
                    var serviceUrl = 'rest/default/V1/carts/mine/estimate-shipping-methods',
                    payload = JSON.stringify({
                            address: {
                                'city': 'New York',
                                'country_id': 'US',
                                'postcode': '98001',
                            }
                        }
                    );
                    self.getRate(payload,serviceUrl);
                });
            },
            getRate: function (payload,serviceUrl) {
                storage.post(
                    serviceUrl, payload, false
                    ).done(
                        function (result) {
                            console.log(result);
                        }
                    ).fail(
                        function (response) {
                            errorProcessor.process(response);
                        }
                    );
            },
        });
        return $.mage.estimateRate;
    });

    After successfully run. You can see rates in response. I hope it will clear that how to get estimate shipping rates through js and also you can call other web api.

    estimate shipping rates

    Thanks for reading this blog.If you get any issue and query then feel free to add a ticket or comment.

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home