Magento 2 how to do minicart ajax update
Question
Is there any way to update the mini cart with ajax without update button.
I am using Magento 2.1.7 how to do mini cart ajax update when qty increment(+) and decrement(-) inside the mini cart, as qty increment(+) and decrement(-) inside the mini cart product price and the total must change without clicking on update
Thanks in advance
La solution
There are two Methods of updating the minicart
Method 1: Using sections.xml
Create sections.xml file under app/code/Vendor/Module/etc/frontend
directory
<?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="module/ajax/index">
<section name="cart"/>
</action>
</config>
Note: Put your ajax call URL in place of 'module/ajax/index'
Method 2: Using customerData dependency in the script tag
<script>
require([
'jquery',
'Magento_Customer/js/customer-data'
], function ($, customerData) {
$.ajax({
type: "post",
url: "your_url",
data: {data : yourData},
cache: false,
success: function(response) {
// reload the minicart
var sections = ['cart'];
customerData.reload(sections, true);
}
});
});
</script>
Autres conseils
Modify sidebar.js file. Find this code:
events['keyup ' + this.options.item.qty] = function (event) {
self._showItemButton($(event.target));
};
And change it to:
events['keyup ' + this.options.item.qty] = function (event) {
self._updateItemQty($(event.currentTarget));
};
Now it won't show update button and will update minicart automatically without page refreshing