WooCommerce AJAX add to cart – Step-by-Step Tutorial

Some weeks ago we talked about how to add the cart function programmatically to boost your sales. Today, we’ll have a look at how to implement AJAX in the Add to cart button in WooCommerce products. This will improve user experience and the overall sales process, which will also help you optimize your store and increase your revenue.

Nowadays, if you want to run a successful store, it’s key that your site updates the cart dynamically. Otherwise, every time a user adds a product to the cart the page will reload making the buying process very slow and increasing the chances of customers dropping out.

That’s why revamping your store with the WooCommerce AJAX add to cart function is a must to reduce cart abandonment and increase your sales. In this guide, we’ll show you how to do it step-by-step.

Benefits of AJAX in WooCommerce

So to sum up, the benefits of using AJAX in your store are:

  • Reduce server load and bandwidth
  • Speed up the buying process
  • Improve customer experience
  • Reduce cart abandonment
  • Increase conversion rates

Tutorial: WooCommerce AJAX add to cart

To apply the AJAX add to cart function in WooCommerce there are two options:

  1. With a plugin
  2. Coding it yourself

Let’s have a look at each method.

1) AJAX add to cart with a plugin

If you don’t have experience coding or you prefer an easy solution, using a plugin is an excellent choice. Simply download our AJAX add to cart WooCommerce plugin, install it and the software will do the rest.

Ajax add to cart for WooCommerce

AJAX add to cart for WooCommerce is one of the best plugins to add AJAX to the WooCommerce add to cart button. This tool allows shoppers to include single or variable products to their carts without having to reload the site every time.

What’s even better is that it runs smoothly in 99% of WordPress themes and it doesn’t require any initial set up. Once you install it, it’ll be ready to go.

2) Code it yourself

Do you have some coding skills and prefer to customize your WooCommerce AJAX add to cart button? In this guide, we’ll show you how to do it step-by-step.

A) Install a child theme

The first thing you need to do is create a child theme. If you don’t have one, you can use a plugin. There are several of them so just pick the one you like best and install it in your store.

Why should you install a child theme? Because if you directly customize the theme’s files, the next time you update the theme, the new files will replace your changes and all your customizations will be lost. However, if you customize the child theme, the modifications won’t be overridden.

B) Include JavaScript (JS) file

In the functions.php file of the child theme, include a JavaScript file by using the wp_enqueue_script hook. This is one of the most popular hooks that WordPress offers to customize websites.

Let’s have a look at the script that includes the ajax_add_to_cart.js file below:

function ql_woocommerce_ajax_add_to_cart_js() {

    if (function_exists('is_product') && is_product()) {  

       wp_enqueue_script('custom_script', get_bloginfo('stylesheet_directory') . '/js/ajax_add_to_cart.js', array('jquery'),'1.0' );

    }

}

add_action('wp_enqueue_scripts', 'ql_woocommerce_ajax_add_to_cart_js');

With the conditional if (function_exists(‘is_product’) && is_product()) in line 2, you make sure that the JQuery is only applied on a product page.

C) Create a JS file

Once you’ve done that, create the file you included in the previous step. Just go to your cPanel and then to the child theme folder. After that, follow the route wp_content /themes/ folder. There, create a new folder in the child theme called js, and then a file inside it with the same name you used in the hook ajax-add-to-cart.js.

Keep in mind that this step also works even if you use an FTP client. If your child theme already has a JS folder, you can use it without creating a new one.

D) The JQuery/JS file

The next step is to work on the JQuery file that you’ve uploaded in your child theme. That file is empty so you need to add scripts.

First, prevent the add to cart button from reloading the page with the following script:

$('.single_add_to_cart_button').on('click', function(e) { 

    e.preventDefault();

});

Please note that we use the $(‘.single_add_to_cart_button’) selector to trigger the AJAX call when the button is clicked. You must understand this because all the following script will go inside this function.

E) JQuery WooCommerce AJAX add to cart on single products

So the full JQuery script for AJAX add to cart on single products is:

jQuery(document).ready(function($) {

    $('.single_add_to_cart_button').on('click', function(e){ 

    e.preventDefault();

    $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: 'ql_woocommerce_ajax_add_to_cart',

            product_id: product_id,

            product_sku: '',

            quantity: product_qty,

            variation_id: variation_id,

        };

    $.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]);

                } 

            }, 

        }); 

     }); 

});

F) The PHP script

Afterward, you need the PHP handler. The best way is to use some of the WooCommerce filter hooks to build your add to cart function. This time you’ll do it using AJAX.

Simply copy and paste the following script in the functions.php file of the child theme below the previous script we used to include the JS file.

add_action('wp_ajax_ql_woocommerce_ajax_add_to_cart', 'ql_woocommerce_ajax_add_to_cart'); 

add_action('wp_ajax_nopriv_ql_woocommerce_ajax_add_to_cart', 'ql_woocommerce_ajax_add_to_cart');          

function ql_woocommerce_ajax_add_to_cart() {  

    $product_id = apply_filters('ql_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('ql_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('ql_woocommerce_ajax_added_to_cart', $product_id);

            if ('yes' === get_option('ql_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('ql_woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id));

                echo wp_send_json($data);

            }

            wp_die();

        }

That’s it! You’ve just created your WooCommerce AJAX add to cart button! But how do you know that you’ve done everything correctly? You can check it easily. When you click on the add to cart button, the product should be added to the cart without reloading the page.

Conclusion

All in all, if you want to optimize your store, the WooCommerce AJAX add to cart function is a must. The easy way to apply it is by using the AJAX add to cart WooCommerce plugin. However, if you have coding skills, you can code AJAX add to cart yourself with a child theme and a bit of PHP as described above. Both options are excellent so choose the one that better suits your needs and skills.

This will help you improve user experience and increase your conversion rates. Please let us know your thoughts in the comments section below.

Finally, for more guides about WooCommerce, we recommend you check out our guides on how to add WooCommerce products and how to create default product attributes in WooCommerce.