With the growing use of the internet and technology, several changes & enhancement happen into design, layout, and code to provide a better & a richer experience to the users. Also, Magento moved smartly with concepts like knockout js, AJAX other add ons that allows web applications to send and retrieve data from a server asynchronously without refreshing or reloading. This technique helps reducing server request and saves time by reloading only one portion or section of the webpage.
For example, we have one extension in Magento 2 that offers Ajax login functionality and we want to restore old cart items once a user successfully login to their account. To do the same we only need to refresh a mini cart only, not the whole page.
By default, Magento 2 creates a small group of data and each group has a unique name/key. So, if we want to refresh a particular section we can use its group key to refresh data. In all new Magento 2, it stores data at both hands, so we also need to update local storage data of browser if we want to refresh a particular portion.
To do the same, first you need to create “di.xml” at this path.
<argument name="sectionSourceMap" xsi:type="array">
<item name="cart" xsi:type="string">Magento\Checkout\CustomerData\Cart</item>
<item name="directory-data" xsi:type="string">Magento\Checkout\CustomerData\DirectoryData</item>
Now, in above code we just register cart and directory-data in customer Data section. For that we need to create section.xml using below code at this path.
So, now whenever we call action like “ajaxlogin/index/getlogin” Magento will consider the current cart section is outdated and it re-initialize the cart section.
You can also refresh the cart section on each request, by using * instead of action.
That’s it for today, Let us know if you are facing an issue while implementing using this code by commenting below.