For a long time, jQuery has been the most popular JavaScript library for web developers. It is lightweight and easy to use. But what if you need to do something, once your product has been added successfully in cart. While I was working in Elementor, I faced an issue, if the products are updated via Ajax in Elementor Built product page, you will not see notification that product is added to cart or something went wrong means error message. In this article, we will learn how to update jQuery after WooCommerce AJAX cart updated.
JavaScript Code
The WooCommerce scripts have several custom events built in. Your own script can listen to these events and run your own code when they are triggered.
I found AddToCartHandler JavaScript code after digging into WooCommerce. Follwing Handlers can help you to something once you click on add to cart button or remove from cart, or product added to cart. Looking at following handlers (Tested and works):
// WooCommerce handle Class
/**
* AddToCartHandler class.
*/
var AddToCartHandler = function() {
this.requests = [];
this.addRequest = this.addRequest.bind( this );
this.run = this.run.bind( this );
$( document.body )
.on( 'click', '.add_to_cart_button', { addToCartHandler: this }, this.onAddToCart )
.on( 'click', '.remove_from_cart_button', { addToCartHandler: this }, this.onRemoveFromCart )
.on( 'added_to_cart', this.updateButton )
.on( 'ajax_request_not_sent.adding_to_cart', this.updateButton )
.on( 'added_to_cart removed_from_cart', { addToCartHandler: this }, this.updateFragments );
};
I test with ‘.remove_from_cart_button’, ‘.add_to_cart_button’, ‘added_to_cart’ , ‘ajax_request_not_sent.adding_to_cart’, ‘removed_from_cart’. Put your code in JavaScript file and do what you want.
// change the handler as needed
jQuery(document.body).on('added_to_cart', function () {
//do something
console.log("We are here");
});
WooCommerce AJAX request is an API that allows you to send data to the server without reloading the page. This is accomplished by using JavaScript and jQuery. WooCommerce AJAX request can be used to query the database, send emails, and perform other tasks which do not require user interaction. This is useful for tasks such as sending out a daily email digest of new orders, processing abandoned carts and updating order statuses.