fbpx

“Add to cart” with Woocommerce and AJAX step by step

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.

Ajax add to cart for WooCommerce

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.

Direct Checkout for WooCommerce

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.

Privacy Preference Center