WooCommerce has an option to run various UI actions via ajax.
If you are developing a theme and want to update your own elements during Woo ajax calls you will want to add the following hook:
add_filter('woocommerce_add_to_cart_fragments', 'my_woocommerce_add_to_cart_fragments');
function my_woocommerce_add_to_cart_fragments($fragments) {
$fragments['#my-dom-element'] = '<div id="my-dom-element">Some new markup with some computed value.</div>';
return $fragments;
}
In the hooked function add a new key to the array:
- the key is an element selector and will be directly passed to
jQuery()
- the value is an HTML string that will be directly passed to
jQuery().replaceWith()
Make sure the HTML string contains the selector from the key, because the JS will replace the matching element with the new element. Basically it does this:
$.each(fragments, (key, value) => $(key).replaceWith(value))
How to show and update the mini-cart (real use case):