Woocommerce - Product Page - How to create AJAX on "Add To Cart" button?

Woocommerce - Product Page - How to create AJAX on "Add To Cart" button?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

WooCommerce - Product Page - How to create AJAX on "Add To Cart" button?

By default, adding a product to the cart on a single product page triggers a full page reload. While the archive or category pages leverage JavaScript events and jQuery to handle this seamlessly, the single product template often relies on form submissions that refresh the entire window. This behavior breaks the shopping flow, especially when you want to implement custom actions like redirecting to the cart immediately after adding an item with selected attributes.

To replicate the smooth experience found on archive pages, you need to intercept the click event before the default form submission occurs and handle the response via AJAX. The core mechanism relies on the wp_ajax_add_to_cart endpoint, which is already active by default in WooCommerce for single products. However, if you are building a custom button—such as a "Take Me Home" action that adds an item to the cart and redirects—you must ensure the request is processed asynchronously.

Intercepting the Click Event

The most robust way to handle this without relying on deprecated methods like window.location.href (which forces a reload) is to listen for the click event on your specific button element. You can attach a handler that prevents the default form submission and initiates an AJAX request using jQuery or native Fetch API.

If you are working within a theme or plugin, ensure you enqueue your custom script in the footer with wp_enqueue_script. Your script should look something like this:

jQuery(document).ready(function($) {
    // Select your custom button, replacing '.my-custom-cart-btn' with your actual selector
    $('.my-custom-cart-btn').on('click', function(e) {
        e.preventDefault(); // Stop the default form submission
        
        var $button = $(this);
        var formData = {
            'add_to_cart': true,
            // Include any necessary product ID or attributes if handling complex logic
            '_wpnonce': wc_add_to_cart_params.nonce 
        };

        $.ajax({
            url: wc_add_to_cart_params.ajax_url,
            type: 'POST',
            data: formData,
            success: function(response) {
                // Handle success: Redirect to cart and show animation
                window.location.href = wc_add_to_cart_params.cart_url;
                
                // Optional: Trigger the bag shake animation if you have custom CSS/JS
                // $('.woocommerce-cart-form').shake(); 
            },
            error: function(response) {
                // Handle errors, such as stock issues or validation
                alert('Could not add product to cart.');
            }
        });
    });
});

Handling the Response and Animation

When the AJAX request succeeds, WooCommerce typically returns a JSON object indicating success. In your success callback, you can redirect the user to the cart URL using window.location.href. This mimics the behavior seen when hovering over the bag icon in the menu header.

To add the "shake" effect to the bag image upon successful addition, you need to verify if such an animation exists in your theme's assets or implement a custom CSS keyframe animation triggered by JavaScript. If your theme lacks this, you can create a simple class toggle:

.bag-shake {
    animation: shake 0.5s ease-in-out;
}

@keyframes shake {
    0% { transform: translateX(0); }
    25% { transform: translateX(-5px) rotate(-5deg); }
    50% { transform: translateX(5px) rotate(5deg); }
    75% { transform: translateX(-5px) rotate(-5deg); }
    100% { transform: translateX(0); }
}

Then, in your AJAX success handler, you can dynamically add the class to the bag container:

success: function(response) {
    // Redirect logic
    window.location.href = wc_add_to_cart_params.cart_url;
    
    // Add shake effect if needed before redirect or on a specific element
    $('.woocommerce-mini-cart__buttons .cart-icon').addClass('bag-shake');
}

Trade-offs and Considerations

One significant trade-off is the reliance on jQuery. While wc_add_to_cart_params provides utility variables, modern development often prefers vanilla JavaScript or Fetch API to reduce dependency bloat. However, sticking with jQuery ensures compatibility with existing WooCommerce scripts that might expect it.

Another pitfall is handling the nonce (_wpnonce). WooCommerce security relies on this token to prevent CSRF attacks. Always ensure your AJAX payload includes the current nonce from wc_add_to_cart_params.nonce or the admin nonce if configured differently in your theme setup. Failing to include this will result in a 403 Forbidden error, breaking the user experience immediately.

Finally, consider the timing of the redirect. If you redirect immediately upon success, the user never sees the confirmation message WooCommerce might display on the page. If preserving that feedback is important, delay the redirect or use setTimeout to show a toast notification before moving the user to the cart page. This balances the seamless UX with immediate feedback for the customer.

Our network