WooCommerce Ajax add to cart

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 help you improve user experience and the sales process, which will also help you optimize your store and boost 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. 

Tutorial: WooCommerce Ajax add to cart

To apply the WooCommerce ajax add to cart function you have two options:

Use a plugin

If you don’t have experience coding or you prefer an easy solution, using a plugin is a good 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”. What’s even better is that it runs smoothly in 99% of WordPress themes and it doesn’t require any initial set up. This means that once you install it, it’ll be ready to go.

Code it yourself

For those who have some coding skills and prefer to customize their WooCommerce Ajax add to cart button, we’ll give you a detailed step by step process that you can follow. 

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

Include JavaScript 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 in a product page.

Create JS file

Once you’ve done that, create the file you’re including in the previous step. Just go to your cPanel and then to the Child Theme folder. Then, follow the route wp_content /themes/ folder.

Once there, create a new folder in 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. And if your Child Theme already has a JS folder, you can use it.

The JQuery 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, deactivate the conventional “add to cart” button behavior 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. It’s important that you understand this because all the following script will go inside this function.

So the full JQuery script 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]); 

                } 

            }, 

        }); 

     }); 

});

The PHP script

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

Simply copy and paste the script below 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(); 

        }

Conclusion

That’s it! You’ve just made your WooCommerce Ajax add to cart button! You’re probably thinking how do you know that you’ve done everything correctly. When you click on the “add to cart” button, the product will be added to the cart without reloading the page.

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