Add an Item to 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 to add a variant and subscription properties to the Shopify cart.

Add a listener to the add to cart link button.

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 and/or order info in our back end within a few minutes.


     addItemToCart(949931647 , 1, "1", "Months", "491")
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
      type: 'POST',
      url: '/cart/add.js',
      data: data,
      dataType: 'json',
      success: function() { 
          window.location.href = '/cart'; 

The subscription_id tells our back end which subscription the product is associated to. From the ReCharge Dashboard by going to Rulesets and choosing the ruleset you've created. Select to Open Advanced Settings and you will see the subscription_id at the bottom.

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. However if the price is different you will need to use the hidden auto renew one. Use the following:
{{ variant.metafields.subscriptions.discount_variant_id }}

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.

Warning: If you have a different price between the original and auto-renew products, you will need to add the hidden auto-renew version you use in the liquid code here: {{ variant.metafields.subscriptions.discount_variant_id }}

If you are using subscription-only, you will not need this.

Still stuck? How can we help? Still stuck? How can we help?