WooCommerce AJAX add to cart on product page – variable products

I’m trying to make an AJAX add to cart button for WooCommerce on the product pages, with variable products. It’s possible to add a product to cart using AJAX by doing the following (in jQuery)

var data = { 
    action: 'woocommerce_add_to_cart', 
    product_id: p_id, 
    quantity: quantity 
}; 

$.post( "/wp-admin/admin-ajax.php", data, function( response ) { 

    if ( ! response ) 
        return; 

});

However I’m trying to adapt this to also work for variable products (on the product page, not the archive page) and this is what I have so far:

Read More
var params = { pa_size:'500g-resealable-pouch', pa_flavour:'chocolate' }; 
var variationParams = $.param( params ); 

var data = { 
    action: 'woocommerce_add_to_cart', 
    product_id: p_id, 
    quantity: quantity, 
    variation_id: var_id, 
    variation: variationParams 
}; 

$.post( "/wp-admin/admin-ajax.php", data, function( response ) { 

    if ( ! response ) 
        return; 

});

All this does is adds the product to the cart but it ignores the variation, so doesn’t put “Size: X, Flavour: Y” into the basket!

I know I’m supposed to send an array to the woocommerce_add_to_cart function, but I can’t figure out how to send the associative array via AJAX. I’ve read a bit about $.param but it doesn’t seem to work.

Note that I want to use this function rather than post to the “add_to_cart_url” because that method makes it ouput “Product added to cart” messages all over the place.

Related posts

Leave a Reply