woocommerce add to cart in javascript

To add a product to a WooCommerce cart using JavaScript, you can use the wc_add_to_cart_params object that is already defined on the page by WooCommerce. Here's an example:

index.tsx
jQuery(document).ready(function($) {
  $('.add-to-cart-btn').click(function(e) {
    e.preventDefault();

    var product_id = $(this).data('product_id');
    var quantity = $(this).data('quantity');
    var variation_id = $(this).data('variation_id');
    var variation = $(this).data('variation') || {};

    var data = {
      action: 'woocommerce_ajax_add_to_cart',
      product_id: product_id,
      quantity: quantity,
      variation_id: variation_id,
      variation: variation
    };

    $.post(wc_add_to_cart_params.ajax_url, data, function(response) {
      if (!response.error) {
        window.location.href = wc_add_to_cart_params.cart_url;
      }
    });
  });
});
683 chars
25 lines

The code above binds a click event to all elements with the class add-to-cart-btn. It grabs the product ID, quantity, and variation ID (if applicable) from the data attributes on the clicked element, and then sends an AJAX request to the WooCommerce server to add the item to the cart. If there are no errors in the response, it redirects the user to the cart page. You can customize this code to fit your specific needs.

gistlibby LogSnag