How to trigger a minicart update after adding to cart

Thanks for your help :)

I have found how to trigger it, you need to set up a sections.xml inside etc/frontend of your module that tells Magento which sections to update for a given Ajax call. Here is an example;

<?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="[frontName]/[ActionPath]/[ActionName]">
        <section name="cart"/>
    </action>
</config>

After my Ajax call has finished to [frontName]/[ActionPath]/[ActionName] Magento makes another call to /customer/section/load passing the sections to load.

By default it requests any messages but if you have set up your sections.xml correctly you will also see the section names you have defined in there as well.


This isn't directly related to the question, but if you are updating the cart via AJAX calls in normal Magento require.js files, you can require the Magento_Customer/js/customer-data object and ask the minicart to refresh this way, as well:

<script>
    require([
        'Magento_Customer/js/customer-data'
    ], function (customerData) {
        var sections = ['cart'];
        customerData.invalidate(sections);
        customerData.reload(sections, true);
    });
</script>

Source: https://github.com/magento/magento2/issues/5621


In storefront if you dive in source in minicart area

<div data-block="minicart" class="minicart-wrapper">
  <a class="action showcart" 
   data-bind="scope: 'minicart_content'">
     ... 
  </a>

   <script type="text/x-magento-init">
   {
    "[data-block='minicart']": {
        "Magento_Ui/js/core/app": {"components":{....}
     }
   }
</script>
</div>

As you can see here magento2 execute components inside script tag and dynamic bind data to block minicart use knockoutJs

Somethings interesting i discover

\vendor\magento\module-checkout\view\frontend\layout\default.xml

From Checkout layout. It define a component for minicart-content to getdata Continue see Magento_Checkout/js/view/minicart you will see

.....
$('[data-block="minicart"]').on('contentLoading', function(event) {
      addToCartCalls++;
      self.isLoading(true);
});
.....

Tags:

Magento2