In this tutorial, you will learn how to use WooCommerce's AJAX events to improve user interactions.
Depending on your setup, and on the event in question, these events are trigged on the shop page, single product page, cart page, checkout page... anywhere where there are AJAX interactions related to WooCommerce.
You will be able to run custom JavaScript functions like updating layouts or initiating other dynamic actions post-AJAX update.
Common WooCommerce AJAX Events
update_cart
This event is triggered when cart quantities are updated.
updated_wc_div
Fired after the AJAX update of the cart totals.
updating_cart
Triggered manually before the AJAX request to update the cart.
applied_coupon & removed_coupon
These events fire after a coupon is applied or removed respectively.
wc_fragments_loaded & wc_fragments_refreshed
Occur when parts of the page are updated with new HTML fragments.
added_to_cart
Fired when a product is added to the cart from the shop page.
removed_from_cart
Triggered when a product is removed from the cart via AJAX from the mini-cart.
checkout_error
Occurs when there is an AJAX error during checkout.
checkout_updated
Fired when checkout details are updated such as changes in shipping method or payment details.
How to Use These Events in Your Code
Example: Listening to the updated_wc_div Event
<script> /* Please login to get the code * The code will be for the How To Use WooCommerce JavaScript AJAX Events tutorial * Found at this URL https://element.how/woocommerce-javascript-ajax-events/ */ </script>
Attach the listener to the document body and specify the event to run your function updateLayout() after the cart is updated.
Quick Start
To quickly get started and easily find out which event you need, and when each event is fired, navigate to the front end of your WooCommerce site, open the browser console (F12 on Chrome, Option + ⌘ + C on Safari), and paste the following jQuery code there, then press Enter.
<script> /* Please login to get the code * The code will be for the How To Use WooCommerce JavaScript AJAX Events tutorial * Found at this URL https://element.how/woocommerce-javascript-ajax-events/ */ </script>
Now, interact with your cart by adding or removing products, applying or removing coupons, and updating quantities. The logs in the console will show up at various steps of these processes, helping you to understand when and where these events are triggered.
Important: when running code in the console like this, it's only active for the current page load. As soon as the page location is changed or the page is refreshed, it's not there. You need to Paste + Enter to run it again.
Conclusion
I hope you have found this helpful!
Cheers!