Add to Cart with Quantity Using AJAX in WooCommerce

Improve your WooCommerce UX by allowing customers to select quantity and add products using AJAX without a full page refresh. Here’s how to set it up.

AJAX Add to Cart with Quantity – Quick Setup Guide

1. JavaScript for AJAX Cart

Create custom-ajax-add-to-cart.js in your theme or plugin directory. Use this:

(function ($) {
  function handleAjaxAddToCart() {
    $(document).on('submit', 'form.cart', function (e) {
      e.preventDefault();

      var $form = $(this);
      var quantity = $form.find('input[name="quantity"]').val();
      var data = $form.serialize();

      $.ajax({
        type: 'POST',
        url: wc_add_to_cart_params.ajax_url,
        data: data + '&add-to-cart=' + $form.data('product_id'),
        beforeSend: function () {
          $form.removeClass('added-to-cart').addClass('loading');
        },
        complete: function () {
          $form.removeClass('loading');
        },
        success: function (response) {
          if (response && response.fragments) {
            $.each(response.fragments, function (key, value) {
              $(key).replaceWith(value);
            });
          }
        },
      });
    });
  }

  $(document).ready(function () {
    handleAjaxAddToCart();
  });
})(jQuery);
2. Register Script in Theme

Include the file using this code in functions.php:

function register_ajax_cart_script() {
  if (is_shop()) {
    wp_enqueue_script('ajax-cart-script', get_stylesheet_directory_uri() . '/custom-ajax-add-to-cart.js', array('jquery'), '1.0', true);
  }
}
add_action('wp_enqueue_scripts', 'register_ajax_cart_script');
3. Product Loop Update

Edit your shop page template to insert quantity fields:

<?php while (have_posts()) : the_post(); $product = wc_get_product(get_the_ID()); ?>

  <div <?php wc_product_class('product-item'); ?>>
    <form class="cart" data-product_id="<?php echo esc_attr(get_the_ID()); ?>">
      <div class="quantity">
        <input type="number" name="quantity" value="1" class="input-text qty text" step="1" min="1">
      </div>
      <button type="submit" class="button">Add to Cart</button>
    </form>
  </div>

<?php endwhile; ?>
4. Testing Time

Reload your WooCommerce shop, pick a quantity, and click “Add to Cart.” The item will be added without reloading the page.

Useful Note

Enable archive AJAX cart buttons via WooCommerce → Settings → Products. If you’re using a heavily customized theme, you may need to tweak templates.

 

Leave a Comment

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

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.