# Add to Cart Without a Page Reload on Product Pages

> Adds simple products to the cart in the background from the product page, updating the mini cart and showing a confirmation instead of reloading the page.

- Type: PHP
- Runs: Run everywhere
- Category: [WooCommerce](https://wpide.com/library/category/woocommerce/)
- Requires: WooCommerce
- Tags: woocommerce, ajax, cart, ux
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/woo-ajax-add-to-cart-single/

## Code

```php
add_action( 'wp_footer', function () {
    if ( ! function_exists( 'is_product' ) || ! is_product() ) {
        return;
    }
    ?>
    <script>
    ( function () {
        var form = document.querySelector( '.product-type-simple form.cart' );
        if ( ! form || ! window.fetch ) { return; }
        form.addEventListener( 'submit', function ( event ) {
            var button = form.querySelector( '[name="add-to-cart"]' );
            if ( ! button ) { return; }
            event.preventDefault();
            var data = new FormData( form );
            data.set( 'product_id', button.value );
            data.delete( 'add-to-cart' );
            button.classList.add( 'loading' );
            button.disabled = true;
            fetch( <?php echo wp_json_encode( WC_AJAX::get_endpoint( 'add_to_cart' ) ); ?>, { method: 'POST', body: data, credentials: 'same-origin' } )
                .then( function ( response ) { return response.json(); } )
                .then( function ( result ) {
                    if ( ! result || result.error ) { form.submit(); return; }
                    if ( window.jQuery ) { jQuery( document.body ).trigger( 'added_to_cart', [ result.fragments, result.cart_hash, jQuery( button ) ] ); }
                    var note = form.querySelector( '.wpide-added' ) || form.appendChild( document.createElement( 'p' ) );
                    note.className = 'wpide-added';
                    note.setAttribute( 'role', 'status' );
                    note.innerHTML = <?php echo wp_json_encode( esc_html( 'Added to your cart.' ) . ' <a href="' . esc_url( wc_get_cart_url() ) . '">' . esc_html( 'View cart' ) . '</a>' ); ?>;
                } )
                .catch( function () { form.submit(); } )
                .finally( function () { button.classList.remove( 'loading' ); button.disabled = false; } );
        } );
    } )();
    </script>
    <?php
} );
```

## Notes

Applies to simple products only, and the mini cart refreshes when WooCommerce's cart fragments script is loaded.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Add to Cart Without a Page Reload on Product Pages" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
