shopify add to cart in javascript

To add a product to the cart in Shopify using JavaScript, you can use the Shopify AJAX API.

Here's an example code:

index.tsx
// Replace this with the product ID you want to add to cart
var productId = 123456;

// Replace this with the quantity you want to add to cart
var quantity = 1;

jQuery.ajax({
  type: 'POST',
  url: '/cart/add.js',
  dataType: 'json',
  data: {
    quantity: quantity,
    id: productId
  },
  success: function() {
    // Redirect to the cart page after successful addition
    window.location.href = '/cart';
  },
  error: function(xhr) {
    // Show an error message
    alert(xhr.responseJSON.description);
  }
});
519 chars
24 lines

In this example, we use the jQuery library to make an AJAX request to the /cart/add.js URL with the product ID and quantity as the data parameters. Once the request is successful, it will redirect the user to the cart page.

Note: Make sure to include the jQuery library in your Shopify theme.

gistlibby LogSnag