I’m a fan of the sales rates improvement, and I’m always looking for tips and 3rd party plugins to improve the sales like the products and categories in the menu.
But one of those things that I never understand about WooCommerce, is the way the Add to cart works is the single products. The default function reloads the entire website each time you press the Add to cart button.
I always thought that an ajax add to cart button is a better implementation as it improves the user experience by allowing changes to the pages without having to load them again.
Imagine that each step you take on the web should refer to another page, and another, and another… The more steps and time your e-commerce load, the more you reduce the chances of selling. That’s why we recommend you to use the AJAX technology that makes the actions take place immediately as if we were interacting with a PC program.
Why use AJAX?
- Use less bandwidth
- Reduce server load
- Speed user experience
- Increase your sales!
If you don’t want to go through the whole tutorial, you can download the ready to use one of these plugins:
Ajax add to cart for WooCommerce
The “Ajax add to cart for WooCommerce” is one of those plugins for WooCommerce you need in your list. This plugin allows users to include single products or variable products in the cart without the need to reload the entire site each time.
WooCommerce Direct Checkout
If you’re looking for an all in one solution we recommend you to install the “WooCommerce Direct Checkout” plugin. It allows you to simplify the checkout process by skipping the shopping cart page.
Ajax add to cart for products
1. Add Javascript File
We will start by including this javascript in your website, so add this code in your functions.php file.
function woocommerce_ajax_add_to_cart_js() { if (function_exists('is_product') && is_product()) { wp_enqueue_script('woocommerce-ajax-add-to-cart', plugin_dir_url(__FILE__) . 'assets/ajax-add-to-cart.js', array('jquery'), '', true); } } add_action('wp_enqueue_scripts', 'woocommerce_ajax_add_to_cart_js', 99);
2. Create Javascript File
After adding the javascript, create a new folder in your child theme called “JS” and add a new javascript called “ajax-add-to-cart.js”.
If you have doubts about how to create a child theme, you can consult the linked tutorial from wp.rocks.
Add jQuery to avoid recharging
Apply this code to prevent the button from sending the information to the database and reloading the page.
(function ($) { $( document ).on( 'click', '.single_add_to_cart_button', function(e) { e.preventDefault(); }); })(jQuery);
Add the product to the cart
The jQuery will be used to collect the information from the website and add a product from the site to the cart. Include this code inside the previous code that hooks in the add to cart single product button event to collect the product data.
$thisbutton = $(this), $form = $thisbutton.closest('form.cart'), id = $thisbutton.val(), product_qty = $form.find('input[name=quantity]').val() || 1, product_id = $form.find('input[name=product_id]').val() || id, variation_id = $form.find('input[name=variation_id]').val() || 0;
Now we will prepare the data to interact with the Ajax WordPress function. This feature allows a web page to communicate with your server without reloading the page.
With Ajax applications on the web can exchange data with the server without interfering with the existing web page.
var data = { action: 'woocommerce_ajax_add_to_cart', product_id: product_id, product_sku: '', quantity: product_qty, variation_id: variation_id, };
Ajax Add to cart event
After this code where we define an array with all required variables, we will trigger the add to cart event, just in case a theme is using this function to make any changes.
$(document.body).trigger('adding_to_cart', [$thisbutton, data]);
Ajax Add to cart function
Here is where the magic begins. We will trigger the WooCommerce add to cart function via javascript with the help fo the WordPress ajax interface.
$.ajax({ type: 'post', url: wc_add_to_cart_params.ajax_url, data: data, beforeSend: function (response) { $thisbutton.removeClass('added').addClass('loading'); }, complete: function (response) { $thisbutton.addClass('added').removeClass('loading'); }, success: function (response) { if (response.error & response.product_url) { window.location = response.product_url; return; } else { $(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, $thisbutton]); } }, });
Ajax Add to cart on single products script
(function ($) { $(document).on('click', '.single_add_to_cart_button', function (e) { e.preventDefault(); var $thisbutton = $(this), $form = $thisbutton.closest('form.cart'), id = $thisbutton.val(), product_qty = $form.find('input[name=quantity]').val() || 1, product_id = $form.find('input[name=product_id]').val() || id, variation_id = $form.find('input[name=variation_id]').val() || 0; var data = { action: 'woocommerce_ajax_add_to_cart', product_id: product_id, product_sku: '', quantity: product_qty, variation_id: variation_id, }; $(document.body).trigger('adding_to_cart', [$thisbutton, data]); $.ajax({ type: 'post', url: wc_add_to_cart_params.ajax_url, data: data, beforeSend: function (response) { $thisbutton.removeClass('added').addClass('loading'); }, complete: function (response) { $thisbutton.addClass('added').removeClass('loading'); }, success: function (response) { if (response.error && response.product_url) { window.location = response.product_url; return; } else { $(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, $thisbutton]); } }, }); return false; }); })(jQuery);
3. Add to cart PHP function
Now we will go to the functions.php file of your child theme to add the following code. The intention of this is to update the cart with the information received by the jQuery file.
add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart'); add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart'); function woocommerce_ajax_add_to_cart() { $product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id'])); $quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']); $variation_id = absint($_POST['variation_id']); $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity); $product_status = get_post_status($product_id); if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id) && 'publish' === $product_status) { do_action('woocommerce_ajax_added_to_cart', $product_id); if ('yes' === get_option('woocommerce_cart_redirect_after_add')) { wc_add_to_cart_message(array($product_id => $quantity), true); } WC_AJAX :: get_refreshed_fragments(); } else { $data = array( 'error' => true, 'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id)); echo wp_send_json($data); } wp_die(); }
Ready!
If all the above was complicated, remember that you can download our plugin called WooCommerce Ajax add to cart that allows you to do this.
62 Comments
Add comment Cancel reply
You must be logged in to post a comment.
Im receiving error $thisbutton is not defined
Great job! I copy the code from this tutorial into my theme and I work!
you’re welcome! hope you can improve your sales
hello rhyme, thanks for reporting this issue, it has been fixed now
Hi there, I can’t get this to work. I’m adding the _woocommerce function as you said but it looks like the article was updated and I am confused now. Can you help?
hello nelson, yes the article had some issues, please read it and follow instructions again
kind regards
You are amazing mate! thanks for this plugin. It has helped me to reduce my server load and increase the sales rate
Thanks Munna! this helps us to keep going on 🙂
This tutorial comes to my attention. I’ve installed by curious and it works smoothly!
Hi, exactly what I was looking without modifying any core file but unfortunately it’s not working for me. When I hit Add to Cart, it shows loading spinner but at the same time I get following on the console “VM1391:1 POST http://mysite.com/wp-admin/admin-ajax.php 400 (Bad Request)”
Any idea?
hello Ahmad, can you open a ticket in our support?
http://quadmenu.com/account/support
Realy cool post, thx!
But it breaks, if WooCommerce *Enable AJAX add to cart buttons on archives * isn´t enabled. Add the hooks just ajax is enabled:
// Check if AJKAX is enabled
if ( ‘yes’ === get_option( ‘woocommerce_enable_ajax_add_to_cart’ ) ) {
add_action(‘wp_enqueue_scripts’, ‘wdns_woo_ajax_add_to_cart_js’, 99);
add_action(‘wp_ajax_woocommerce_ajax_add_to_cart’, ‘woocommerce_ajax_add_to_cart’);
add_action(‘wp_ajax_nopriv_woocommerce_ajax_add_to_cart’, ‘woocommerce_ajax_add_to_cart’);
}
Good luck
Thanks!
We will check and correct this issue
Thanks for this info. I had to checked the option “Enable AJAX add to cart buttons on archives “. If I don’t, the JS var named “wc_add_to_cart_params” is not found.
There is a 2nd bug when using variable products: by clicking the (disabled) add2cart button and no variation is selected the WooCommerce alert triggers but the product will be added to the cart by ajax.post.
That can be prevented by adding this exception
[…]
if ( $form.find(‘input[name=variation_id]’).length > 0 && variation_id == 0 ) { return false; }
[…]
directly above
[…]
$.ajax({…
This works for me…
Tried it but it fails for variable products with with one of the attribute options set to “Any”
hello, thanks for reporting this issue, can you share the link of the product?
i am trying this plugin in localhost its not creating same functionality as well as show in video
Hi,
great tutorial. Seems to be working fine.
The only issue im having is, when you add a product with multiple variations the returned fragment only
contains the Product Name, Quantity and Price. I have products with a color and size selection. How can i include that date in the fragment?
Thanks
Pete
hello Pete, can you share the link to the product?
Thank you very much OVIBYTE, works perfectly. Great tutorial!
Works great for adding products to the cart. Only problem I run into is that I use the WooCommerce product addon extension. Data from this plugin is not added to the cart and I can’t figure out how I would add this extra data.
Got any tips for that?
FYI, I fixed it by using the default WooCommerce add to cart functionality. It accepts an extra parameter $cart_item_data, to pass along this extra product data. Which for my case made it easier.
Hi there,
This is working great, just one question .. is it possible to expand the shopping bag content icon after the product is being added? In my theme which i’m using (uncode) i just get the number count bubble above the shopping bag icon in the primary menu, it would be great if it expands it’s content once the product is added
Thank you! Awesome plugin btw
Hi, looks great! Do you have a tutorial for how to add / build the sliding out cart element? Looks really sweet!
HI,
This is a great article.
Thanks for the code it’s working well.
There is just one issue that I am not able to receive the Notice above the product.
Can you please help me sort it out as if there is anything that I missed out.
Love this plugin!
Can you maybe assist me to resolve another issue?
When i add a single product to my card the plugin does its job perfectly!
But for some reason, it does not update the cart until you refresh the page..
Any ideas?
https://idcardprinters.co.za/product/fargo-c50-card-printer/
Regards
Is this still working?
I keep getting $passed_validation = apply_filters(‘woocommerce_add_to_cart_validation’, true, $product_id, $quantity); always returns false.
Can’t seem to find the filter code in the WC base.
Can this be also used with the shortcode ?
Variation are not adding . how to add variations to cart with manual add to cart button
Hi Team
I did as per the procedure Above on the Storefront theme. But even after doing so nothing happened. Can you recommend any other theme for ecommerce which can be used to get this job done.
Thanks for this! Exactly what I needed.
You’re welcome
hello
tank you for this plugin, its awesome, but i have problem that its not working in main page like http://www.mysite.com,
i want its work in all page like : main,shop,category…
please help me that where in the code must be change!!!
Thank you very much!!
Done that but i just have a little trouble:
i can’t delete all the products in my cart.
Let me explain:
1- i had 1 item #1, then a 2nd #2, then a 3rd #3
2- go to chart and delete #1 –> OK(page doesn’t refresh). Delete #2 –> OK (page doesn’t refresh). Delete #3 –> NOK. Page reload and the latest item added is back to chart.
I’ve chech also some forum talking about Ajax and … it might be cache trouble but i don’t have any cache pluggin.
Is there any solution Doctor?
Thanks!
Hi,
Thank you, it work 😉
But i have a probelm with variable product; Each product contain more than one variation and each variation has an image linked with attributes colors and sizes. So the add to cart ajax work perfectly but it take the wrong image.
How can I fix this problem ?
Kind regards
Hello. Great plugin. But it works only on the product page. In my case it’s not a big problem when the product page would reload after adding the product to cart.
The bigger problem is when someony try to by a lot of products one-by-one directly from the shop or category page by clicking add to cart there…
Every time the page is reloading which makes the process of ordering uncomfortable 🙁
Will you add this function to the shop/category pages too?
Thanks
Hey.. guys i am beginner and i want to use this code in my project .. please help me to use this code in project .. please help me…
i am try to make a shopping website for my minear project in college…
if any guys are helps me please contact me.. whatsapp number +91 8719952417
Does anyone know how to keep the cart ajax working when also using ajax product filters? Seems the filter ajax unloads the add-ta-cart ajax…
Hi,
Will this plugin work with Extra Product Options by Rightpress.
After installing the plugin successfully, when products are added to cart the entire list of product options for the product are added to cart NOT just the ones selected on the product page.
Any ideas how to resolve this?
Cheers
Thank you for this, it is great!
One question; is it possible to add to cart on quantity change? I currently have “+” and “-” buttons which control the amount of each item that is added to the cart. I would love to be able to update the cart by only clicking the plus or minus button.
Thank you!
if (response.error & response.product_url) {
Should be:
if (response.error && response.product_url) {
thanks for the fix
Hi can you suggest that if i use your plugin with quick view plugin will it reload the page or not.?
Hi, I installed the plugin and it works, how do I remove the “view cart” button that now appears next to the “add to cart” button on the single product page once I added an item to the cart? I have no need for that option.
Hi, I get the following error when I click the add to cart button. Can you offer some help?
Uncaught ReferenceError: wc_add_to_cart_params is not defined
at HTMLButtonElement. (ajax-add-to-cart.js?ver=5.5.1:25)
at HTMLDocument.dispatch (jquery-3.5.1.min.js:2)
at HTMLDocument.v.handle (jquery-3.5.1.min.js:2)
Thank you, your articles saved some hours for me.
Works Well, Only problem that variation is not added on cart page,
Product is added in cart page without variation.
If you can fix this problem
Thanks 🙂
woocommerce floating cart this also good one and free plugin from wordpress.org
Frequently Bought Together Woocommerce make to multiple product add to cart its also know as Woocommerce Combo Product.
Hi, I’m having the same problem as Melch, it fails for variable products with with one of the attribute options set to “Any” in admin, here’s an example: https://cityshoppe.com/product/natural/
Hi! Everything works great! But cart in the page header (Storefront theme) does not update automatically. I must to reload the page.
Hello,
I used the tutorial and replicated all the steps but the notices don’t appear.
How can I fix it?
Hi!
Thanks for sharing it
It works properly on woocommerce 4.4.1, but if I update it to 4.5.0 (beta) or newer versions, it doesn’t add custom data to the cart, just the product.
site theme is flatsome 3.13.3
is there any update for newer woocommerce versions?
Hello,
I was wondering if it was possible when you click on the “-” button (in my archive page) that removes the quantity of the product in the cart (in ajax)?
I want to reproduce the same system as in the basket, add or delete the ajax quantities with the minus and the plus.
Do you have an idea please?
Hey Thanks for this wonderful information i was exactly looking for this. and i found that same in your blog. i have implemented this in my clients website and it works amazing.
Hey Thanks for this information but I have a question basically I want the products to be listed on the taxonomy page and also with add to cart button using ajax as I came to know that as woocommerce will give by default the ajax add to cart button
Can you clarify this as the default woocommerce feature is not working for me
I am using this on my woocommerce site and works great. However, i have installed the Woocommerce Gift Cards plugin and does not seem to work well with that.
Error Message: “Gift Voucher” cannot be purchased – some required data is missing.
cheers, your code works well 🙂
thank you , good job
Hello Everyone, anyone know that how to add 2 buttons on single product page with two different prices if on click 1 button the price 1 should goes to cart and if click on button 2 the price 2 should goes to cart?
Great buddy thank you so much