X Theme & Pro Theme

Enabling AJAX Add to Cart on single product views, with X overlay

X Theme & Pro Theme7 Comments

One simple tweak I make on many of my Woocommerce based websites is to enable the AJAX add to cart functionality. In many cases, having the user directed to a cart page isn’t ideal for your shop, and a hard reload to the same page is just silly. Someone in the Themeco community asked about how to do this, so I’m sharing the code I use. It can be applied to any site with any theme that doesn’t have this built in already, but my code here has the added perk of including the X/Pro “Added to Cart” overlay. Continuity is good UX, afterall.

Please note this only works on simple type products.

This tip has two files. The first is the custom javascript you need to make it work. You can place this in your customizer, or better yet, save it to a .js file in your child theme and enqueue it only on single product pages.

The second file is your PHP code that can go directly into functions.php in your child theme.

The above code should work as is for you on any X or Pro site. For tweaking from there, one thing I see a lot of people do is toggle their cart off canvas to fly out after an item has been added to cart. While you could put it in the AJAX success function, a better way would be to hook into the javascript event “added_to_cart” to do it globally.

Hope that helps a few of you out, feel free to drop a comment below if needed!

Newsletter

Like what you see? Then get it in your inbox.

  • This field is for validation purposes and should be left unchanged.
Subscribe
Notify of
guest
7 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Thomas

Thanks for sharing. Can you explain how to toggle the cart off canvas after adding an item to the cart?

Thomas

Thank you, I just edited your original JS to this and it works perfect:

Code:
success: function() {
$(document.body).trigger(‘wc_fragment_refresh’);
$(document.body).trigger(‘added_to_cart’);
setTimeout(function() {
button.prop(‘disabled’, false).text(‘In den Warenkorb’);
}, 200);
setTimeout(function() {
$(‘#warenkorb-anchor-toggle’).click();
}, 1000);
},

On another page without off canvas I use this code:

Code:
success: function() {
$(document.body).trigger(‘wc_fragment_refresh’);
$(document.body).trigger(‘added_to_cart’);
setTimeout(function() {
button.prop(‘disabled’, false).text(‘In den Warenkorb’);
}, 200);
setTimeout(function() {
$(location).attr(‘href’,’domain.whatever/cart’);
}, 1000);
},

Thank you!

Thomas

And 2nd question: How to use this code WITH redirect to cart?

German Kokum

thanks for this code

I have been dealing with this tutorial without luck

https://quadmenu.com/add-to-cart-with-woocommerce-and-ajax-step-by-step/

Cavid Muradov

Hi, this is great snippet. Have any chance about variable products?