How to successfully implement Ajax add to cart in WooCommerce

How to successfully implement ajax add to cart in WooCommerce

Full-page reloads can disrupt the shopping flow and frustrate your customers. In this in-depth tutorial, I'll show you three different methods (the default settings, plugins, and custom code) to enable WooCommerce AJAX add to cart in your online store.

If you're looking to add an AJAX add to cart function to WooCommerce, this guide is for you. Here, we'll explore three methods that you can use to enable AJAX add to cart in WooCommerce:

I'll also outline the pros and cons of each method, and answer common questions about adding the AJAX add to cart feature to WooCommerce.

Sounds good? Great, let's jump straight into it.

What is WooCommerce AJAX add to cart?

WooCommerce AJAX add to cart is a feature that allows customers to add products to their shopping carts without requiring a full-page reload. AJAX communicates with your website's server in the background to update the cart contents dynamically. This creates a faster and smoother shopping experience by reducing friction in the purchase process.

Key benefits: AJAX add to cart reduces server load by 56%, lowers bounce rates, increases conversions, and improves overall user experience by eliminating disruptive page reloads.

To illustrate how this works
Let's suppose you run an online clothing store. A customer is browsing on the T-shirt category page and they click the "Add to cart" button for one of the T-shirts.

Without AJAX

  • Clicking "Add to Cart" triggers a full-page reload.
  • The customer loses their place on the page.
  • Loading time creates a frustrating user experience.

With AJAX

  • The selected t-shirt is added to their cart instantly without reloading or redirecting them to the cart page.
  • The header cart icon updates to reflect the added item.
  • A success message appears confirming the action.

How to enable WooCommerce's native AJAX add to cart feature

WooCommerce includes a built-in AJAX add to cart feature that works on Product Archive pages. Product Archive pages are shop, category, and tag pages in WooCommerce. This updates the cart count instantly in the header when customers click the add to cart button. The AJAX request processes in the background without reloading the entire page.

Limitations of WooCommerce's default AJAX add to cart setting

The default WooCommerce AJAX implementation has three major limitations that impact the customer shopping experience:

  • It doesn't work on product detail pages. The default AJAX function only works on Product Archive pages. Single product pages trigger a full-page reload when customers click the add to cart button.
  • It doesn't support quantity selection. Customers cannot choose product quantities directly on Archive pages. The add to cart button only adds one unit of the product. Customers must navigate to individual product pages or manually update quantities in the cart after adding items.
  • It doesn't work for variable products. Variable products are items with size, color, or other options. Customers must navigate to product detail pages to select variation options before proceeding to checkout.

These limitations slow down the shopping process. They create extra steps and friction for customers trying to complete purchases quickly. Many store owners use plugins or custom code to overcome these limitations.

How to enable WooCommerce's default AJAX add to cart setting

WooCommerce's built-in AJAX add to cart feature is disabled on Product Archive pages by default. Here's how to activate it:

  1. In your WooCommerce site's admin, navigate to WooCommerce Settings Products General.
    WooCommerce AJAX add to cart 1

  2. Locate the "Add to cart behaviour" section and tick the "Enable AJAX add to cart buttons on archives" button.
  3. Scroll down the page and press the Save Changes button.

That's it! The buttons on your site's Shop, Category, and Tag pages will use AJAX to add products to the cart. Feel free to head to your site's front end to test it out.

The best WooCommerce AJAX add to cart plugins

WooCommerce's default AJAX add to cart feature provides basic functionality. These plugins extend AJAX capabilities to create a more comprehensive shopping experience:

Quick comparison of AJAX solutions

Solution Price Archive pages Product pages Variable products Bulk quantities Custom layout Best For
WooCommerce default Free Basic stores with simple products
AJAX Add to Cart pugin Free Stores needing AJAX on product pages
WooCommerce Product Table $99/year Catalogs, wholesale, B2B stores
WooCommerce Bulk Variations $99/year Clothing, accessories, variable products
WooCommerce Fast Cart $99/year All stores wanting faster checkout
Custom code Dev Time Stores with dev resources & specific needs

Legend: Full Support | ○ Partial Support | Not Supported

Let's take a more in-depth look at each plugin.

AJAX add to cart for WooCommerce

WooCommerce AJAX add to cart 2

The AJAX add to cart for WooCommerce plugin extends WooCommerce's built-in AJAX functionality to single product pages. The plugin serves more than 20,000 WooCommerce stores and has multiple 5-star ratings. It prevents full-site reloads when customers add simple, variable, or grouped products to their shopping carts from product detail pages.

To use AJAX add to cart for WooCommerce, simply:

  1. Head to Plugins Add New Plugin in your site's admin panel.
  2. Search for the AJAX add to cart for WooCommerce plugin by QuadLayers, then install and activate it.

That's it! Now you can head to product detail pages and test out the AJAX add to cart feature.

Note: AJAX add to cart for WooCommerce fixes the gap in WooCommerce's default AJAX functionality. The plugin does not add quality-of-life improvements or additional features to boost your store's sales and conversion rates. It does not enhance product presentation or remove friction from other parts of the customer journey.

That's where the other WooCommerce AJAX add to cart plugins on our list come in.

WooCommerce Product Table

WooCommerce Product Table sales page screenshot

WooCommerce Product Table is a plugin that displays products in a table-like format with AJAX add to cart functionality. The table layout makes it easier for customers to browse, search, and purchase multiple items simultaneously.

Here's a brief overview of how it works:
WooCommerce Product Table replaces WooCommerce's default store layout with quick product order forms. Customers select products, variations, and quantities using checkboxes. They then use the "Add Selected to Cart" button to add all selected items to their carts using AJAX. The entire process happens without page reloads.

WooCommerce Product Table Variation Prices

The product table layout benefits specific store types. Stores with large product catalogs like clothing retailers use it to display many items at once. Wholesalers use it for bulk ordering. Auto parts retailers use it when customers need to compare and select multiple products quickly.

The table layout simplifies the ordering process. It boosts conversion rates and improves overall user experience (UX) by reducing clicks and page loads.

WooCommerce Product Table's key features

  • Customizable table layout. You can choose the columns and product data displayed in the table including name, price, image, SKU, stock status, and custom fields.
  • AJAX-powered search and filters. Customers filter products by categories, tags, attributes, or custom taxonomies. AJAX powers instant filtering and displays relevant results without page reloads.
  • Support for product variations. Customers select product variations like size, color, or material directly from the table. They add variations to the cart without opening individual product pages.
  • Bulk add to cart. Customers select multiple products and add them to the cart in one click. This feature supports wholesale and bulk-quantity orders.
  • Sorting and pagination. The plugin supports sorting by columns such as price or stock status. Pagination keeps the user interface clean for sites with large product catalogs.
  • Quick product details. The quick view option shows additional product information without leaving the table.

Next steps: Click here to learn more about WooCommerce Product Table.

WooCommerce Bulk Variations

WooCommerce Bulk Variations sales page screenshot

WooCommerce Bulk Variations is a plugin that presents multiple product variations in a table or grid format on WooCommerce product detail pages. Stores selling products with several variations use it to simplify ordering. Common use cases include clothing, accessories, sporting equipment, and wholesale goods.

bulk order variations

WooCommerce Bulk Variations' key features

  • Variation grid display. The plugin displays variations in a grid or matrix format instead of dropdowns. Customers see all attribute combinations at a glance. A clothing store can display a grid with sizes as rows and colors as columns.
  • Bulk quantity selection. Customers enter quantities for multiple variations directly in the grid. They add all selected variations to the cart with one click after selecting quantities.
  • Customizable content and display options. Store owners control which attributes display and how the grid is styled. The plugin pulls descriptions, images, stock levels, and prices automatically. It displays this information in the grid to provide additional details for each variation.
  • AJAX-powered add to cart buttons. WooCommerce Bulk Variations uses AJAX to update stock quantities, pricing, and availability dynamically within the grid. The variation grids are fully responsive across all device sizes.

Next steps: Click here to learn more about WooCommerce Bulk Variations.

WooCommerce Fast Cart

WooCommerce Fast Cart sales page screenshot

WooCommerce Fast Cart is a plugin that replaces WooCommerce's default checkout flow with a streamlined AJAX-powered process. The plugin allows customers to view their cart and complete checkout without leaving the current page.

WooCommerce Express Shop Page fast cart

A pop-up or slide-in modal window appears when customers add items to their cart from any page. Customers review items, adjust quantities, and proceed to checkout without navigating away. This eliminates the need to search for the cart page to initiate checkout.

WooCommerce Fast Cart's key features

  • Quick cart with built-in checkout. The modal popup or slide-in panel allows customers to view carts, make adjustments, and complete checkout on the same page. This reduces checkout steps and lowers cart abandonment rates.
  • AJAX-powered cart updates. The cart updates dynamically when customers adjust quantities, remove products, or apply coupon codes. No full-page reloads occur during these actions.
  • Compatibility with shipping and payment providers. The plugin integrates with WooCommerce shipping methods and payment gateways. Customers see accurate order totals and select preferred payment methods within the cart.
  • Cross-sells and upsell integration. Store owners display relevant cross-sell or upsell suggestions directly in the cart. A customer adding a smartphone sees recommendations for cases, screen protectors, and accessories.
  • Customizable design. Store owners customize the cart layout, colors, and fonts to match store branding. This creates a seamless ordering experience.

Next steps: Click here to learn more about WooCommerce Fast Cart.

Which AJAX solution should you choose?

Use this decision guide to find your perfect AJAX cart solution:

Step 1: Do you have development resources and need custom functionality?

  • YES → Use custom code (full control, requires maintenance)
  • NO → Continue to Step 2

Step 2: Do you only need AJAX on archive pages with simple products?

  • YES → Use WooCommerce default setting
  • NO → Continue to Step 3

Step 3: What's your primary need?

  • AJAX on product pages only → AJAX Add to Cart plugin
  • Bulk/wholesale orders → WooCommerce Product Table
  • Many product variations → WooCommerce Bulk Variations
  • Faster checkout process → WooCommerce Fast Cart
  • All of the above → Combine multiple plugins for comprehensive solution

WooCommerce AJAX add to cart code snippet

Custom PHP and JavaScript snippets enable AJAX add to cart buttons on your site if you have development skills. Custom code requires maintenance with WooCommerce updates. WooCommerce hooks or scripts may change during updates, causing the feature to stop working. Small code errors can break your site or disrupt the user experience.

(If you're not confident in maintaining custom code, skip this section and use the plugin options above.)

Here are the steps to enable the AJAX function on the WooCommerce single product page without triggering a full-page reload.

1. Create the JavaScript File (ajax-add-to-cart.js) in your child theme's /js folder

The JavaScript file may be located in your child theme's /assets folder instead. Create the /js folder if it doesn't exist. Write the exact path to this js file when enqueuing it in PHP in step 2.

This file listens for the "Add to Cart" button click and prevents the default page reload. It triggers an AJAX call to add the product to the cart. The cart updates without reloading the page.

Code snippet:

jQuery(document).ready(function ($) {
    // Trigger on the "Add to Cart" button click
    $("form.cart").on("submit", function (e) {
        e.preventDefault(); // Prevent form submission

        var $this = $(this),
            product_id = $this.find("[name=add-to-cart]").val(),
            quantity = $this.find("input.qty").val() || 1,
            variation_id = $this.find("input[name=variation_id]").val() || 0,
            data = {
                action: "woocommerce_ajax_add_to_cart",
                product_id: product_id,
                quantity: quantity,
                variation_id: variation_id,
            };

        // Show a loading spinner (optional)
        $this
            .find(".single_add_to_cart_button")
            .after('<span class="loading">Loading...</span>');

        // AJAX call
        $.ajax({
            type: "POST",
            url: woocommerce_params.ajax_url || '/wp-admin/admin-ajax.php',
            data: data,
            success: function (response) {
                if (response.error && response.product_url) {
                    window.location = response.product_url;
                } else {
                    // This is key - update fragments, including mini cart
                    if (response.fragments) {
                        $.each(response.fragments, function(key, value) {
                            $(key).replaceWith(value);
                        });
                        $(document.body).trigger('wc_fragments_refreshed');
                    }
                    // Trigger WooCommerce's added_to_cart event and update fragments
                    $(document.body).trigger("added_to_cart", [
                        response.fragments,
                        response.cart_hash,
                    ]);

                    // Optionally: Remove the loading spinner and show success message
                    $(".loading").remove();
                    alert("Product added to cart!");
                }
            },
            error: function () {
                $(".loading").remove();
                alert("There was an error. Please try again.");
            },
        });
    });
});

2. Enqueue the JavaScript

Open your child theme's functions.php file. Use wp_enqueue_script() to load the JavaScript code on your single product pages. This code handles the AJAX request.

Code snippet:

function custom_woocommerce_ajax_add_to_cart_js() {
    if (is_product()) { // Only load the script on single product pages
        wp_enqueue_script(
            'ajax-add-to-cart',
            get_stylesheet_directory_uri() . '/assets/js/ajax-add-to-cart.js',
            array('jquery'),
            null,
            true
        );
    }
}
add_action('wp_enqueue_scripts', 'custom_woocommerce_ajax_add_to_cart_js');

Modify the path ('/assets/js/ajax-add-to-cart.js') according to where you created your js file.

3. Handle the AJAX Request with PHP

Define a function in your child theme's functions.php file to process the incoming AJAX request. This PHP function adds the product to the WooCommerce cart. It sends back updated cart fragments such as the cart total or number of items. These fragments refresh the cart section in the user's view.

Code snippet:

function custom_ajax_add_to_cart_handler() {
    $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 = empty($_POST['variation_id']) ? 0 : absint($_POST['variation_id']);
    $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);

    if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id)) {
        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);
        }

        // Return fragments for updating the cart
        WC_AJAX::get_refreshed_fragments();
    } else {
        // If there's an error, return the product URL for redirect
        wp_send_json(array(
            'error' => true,
            'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id),
        ));
    }

    wp_die();
}
add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'custom_ajax_add_to_cart_handler');
add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'custom_ajax_add_to_cart_handler');

4. Ensure cart fragments are refreshed

WooCommerce automatically handles cart refreshing when products are added via AJAX. Enable WooCommerce's wc-cart-fragments script if the mini-cart or cart fragments are not updating after adding products.

In your child theme's functions.php, add this code:

function enqueue_wc_cart_fragments() {
    if (is_product()) {
        wp_enqueue_script('wc-cart-fragments');
    }
}
add_action('wp_enqueue_scripts', 'enqueue_wc_cart_fragments');

FAQs about WooCommerce AJAX add to cart

Here are answers to common questions about adding AJAX add to cart buttons in WooCommerce.

How does AJAX add to cart impact site performance?

AJAX add to cart impacts WooCommerce site performance in two key ways:

  • Reduced server load from full-page reloads. AJAX eliminates full-page reloads. Each full-page reload forces the server to process requests for all static assets including CSS, JavaScript, and images. AJAX only processes relevant cart data. This reduces data transfer by 56% between server and user device. The result is quicker responses and less strain on website bandwidth.
  • Enhanced site usability. AJAX makes the shopping experience more intuitive and responsive on the front end. Customers receive immediate feedback when adding items to their cart. Updates include mini cart changes, notifications, or cart total adjustments. This eliminates confusion and keeps customers engaged in shopping.

What are the benefits of adding WooCommerce AJAX add to cart?

AJAX add to cart provides technical improvements and business benefits for your WooCommerce store.

It lowers bounce rates

Every second counts in e-commerce. Long delays from page reloads or clunky interactions frustrate customers. Frustrated customers bounce off without completing purchases. AJAX keeps the ordering experience smooth. It reduces the likelihood of customers abandoning their carts.

It increases conversions

An effortless shopping process increases purchase completion rates. AJAX speeds up ordering with instant cart updates. It provides clear visual feedback for customers to take further steps. Customers can add more products or initiate checkout quickly. This keeps customers engaged until checkout and leads to higher conversion rates.

It improves user experience (UX)

Adding products to the cart from Product Archive pages without AJAX takes customers back to the top of the page. AJAX keeps customers in their current position when adding products. They continue browsing and adding products without losing their place. This saves time and improves your site's user experience.

How can I implement AJAX add to cart without a plugin?

Two methods enable AJAX functionality in WooCommerce without plugins:

  • WooCommerce's native AJAX add-to-cart feature enables AJAX for Product Archives including Shop, Category, and Tag pages.
  • Custom PHP and JavaScript code adds custom AJAX add to cart buttons throughout WooCommerce.
Quick Tip: Test AJAX functionality on different devices and browsers after implementation to ensure consistent performance across all platforms.

Upgrade your store with WooCommerce AJAX add to cart

Adding multiple products to a shopping cart without AJAX creates a frustrating customer experience. Full-page reloads cause shopping to feel slow and disruptive, especially in large WooCommerce stores. Even if customers complete purchases, the experience impacts their perception of your store.

This guide explored three methods to enable AJAX add to cart in WooCommerce. We covered WooCommerce's built-in AJAX setting, the best AJAX add to cart plugins, and custom PHP and JavaScript code snippets.

To recap, these are the best plugins to add AJAX add to cart in WooCommerce:

Get started with these options and enable AJAX add to cart in your WooCommerce store today!

 

Please share your thoughts...

Your email address will not be published. Required fields are marked *