Magento – Update price in checkout page without refresh Magento 2

checkoutcontrollersjavascriptmagento2price

I have a controller where I apply some discount on the checkout page.
Now, I can see the price change just after I refresh the page.

I search for a solution, to refresh the price using a Js file.

define([
        'jquery',
        'Magento_Checkout/js/action/get-totals'
        ], function ($, getTotalsAction) {
        "use strict";

          $.ajax({
                method: "post",
                url: demoUrl, //your ajax Url
                data: {/*here post data*/},
                dataType: "html",
                success: function (resp) {
                   //below two lines refershing cart summary
                    var deferred = $.Deferred();
                    getTotalsAction([], deferred); //this function already created in Magento_Checkout/js/action/get-totals.js file
                }

            });

});

But if I insert this script in my controller, nothing happens!

Does anyone have any idea how can an update the price without refreshing the page?

I know by default Magento 2 has a function to do that. When I enter a valid coupon code the price it's updated without refreshing the page!

Best Answer

Use sections.xml in following location vendor/module_name/etc/frontend/sections.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
    <action name="route/controller/actionname">
        <section name="cart"/>
        <section name="checkout-data"/>
    </action>
</config>