Guide to add item to cart with ajax

Adding a subscription item to the cart with ajax

If you want to allow customers to add a subscription product to the cart from a page other than the product page, then you must use an ajax add to cart function. 

We use ajax to add a variant and subscription properties to the Shopify cart
1) add a listener to the add to cart link/button
2) within the listener, call the addItemToCart function, and specify params for:
  •     quantity
  •     variant_id
  •     interval unit (e.g. Months)  
  •     interval frequency (number, set as string )
  •     subscription id (instructions on where to find this below)
We'll read those properties once the order is created and create the customer/order info in our backend within a few minutes.

An example is below:

<script>
$('#add-to-cart-button').click(function(){
     addItemToCart(949931647 , 1, "1", "Months", "491")
})
</script>
<script>
function addItemToCart (variant_id, quantity, shipping_interval_frequency, shipping_interval_unit_type, subscription_id) {
  data = {
      "quantity": quantity,
      "id": variant_id,
      "properties[shipping_interval_frequency]": shipping_interval_frequency, 
	"properties[shipping_interval_unit_type]": shipping_interval_unit_type,            
	"properties[subscription_id]": subscription_id
    }
  jQuery.ajax({
      type: 'POST',
      url: '/cart/add.js',
      data: data,
      dataType: 'json',
      success: function() { 
          window.location.href = '/cart'; 
      }
  });
}
</script>

The subscription_id tells our backend which subscription the product is associated to . You can find the subscription_id from the Recharge dashboard.

For the variant_id it is recommended that you use the variant id of the original product, not the hidden auto-renew product that Recharge creates.

Then you call the function  addItemToCart you need to pass the variant id of the product you're adding, the frequency, and the subscription id.

Adding from an External Site:

If you want to use this ajax code from an external site, you should create a page on Shopify that just has the ajax code and then does a redirect afterwards. This is because you cannot call the Shopify ajax code from an external site, it must be on your Shopify site.

Contact Us Contact Us