jqueryajaxwordpresswoocommerceproduct-variations

Add to cart a product variation via JQuery and Ajax in WooCommerce


I am Unable to add a product variation to cart using jQuery and Ajax. With the code below, the parent variable product is added, but not the variation. For example, I specified one of T-shirt variations (blue) with price of 45$, but at the end, the parent is added with price of 30$.

Cart should show: T-shirt - Blue 45$, but instead it shows: T-shirt 30$.

My code so far:

jQuery(document).ready(function($) {
    $(document.body).on('click', '#button', function(e) {
        const data = {
            product_id: 592,
            quantity: 2,
            variation_id: 1017,
        };

        $.ajax({
            type: 'POST',
            url: wc_add_to_cart_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'add_to_cart' ),
            data: data,
            success: function(res) {
                console.log('added');
            },
        });
    });
});

How to accomplish this with jQuery?


Solution

  • If you look at WC_Ajax add_to_cart method (line 470 to 474), you will see the following:

    if ( $product && 'variation' === $product->get_type() ) {
        $variation_id = $product_id;
        $product_id   = $product->get_parent_id();
        $variation    = $product->get_variation_attributes();
    }
    

    Which means that you don't really need to set in your code the main variable product Id, but you can just set the variation ID as product ID argument and the quantity like:

    jQuery(function($) {
        // wc_add_to_cart_params is required to continue
        if ( typeof wc_add_to_cart_params === 'undefined' ) {
            console.log('Error: wc_add_to_cart_params is not defined.');
            return false;
        }
    
        $(document.body).on('click', '#button', function(e) {
            const data = {
                product_id: 1017, // The variation ID
                quantity: 2,
            };
    
            $.ajax({
                type: 'POST',
                url: wc_add_to_cart_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'add_to_cart' ),
                data: data,
                success: function(response) {
                    // Refresh cart items counter and mini-cart widget
                    $(document.body).trigger('wc_fragment_refresh'); 
                    console.log(response);
                },
                error: function (error) {
                    console.log(error);
                }
            });
        });
    });
    

    Tested and works with a real variation ID.