skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. To follow on from LoicTheAztec’s answer. I needed to include the variation_id otherwise the function add_to_cart_handler_variable would complain and add a wc notice to the frontend.

    I don’t know why one area of WC seems to support variable products whilst another doesn’t; when adding to the cart like this.

    So:

    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
                variation_id: 1017 // variation ID again
                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'); 
                    // [or, if you have the clicked button] Trigger event so themes can refresh other areas.
                    // $(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, $thisbutton])
    
                    console.log(response);
                },
                error: function (error) {
                    console.log(error);
                }
            });
        });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search