Add an item to the cart with Ajax

Learn how to use Ajax to allow customers to add a subscription product to their cart from outside of the product page.

You must use an Ajax add-to-cart function to add a variant and subscription properties to the Shopify cart if you want customers to add a subscription product to the cart from a page other than the product page. This guide provides a reference for your developer on how this can be implemented on your Shopify store.

πŸ“˜

Platform

  • Shopify Checkout Integration

Before you start

  • This guide requires advanced coding knowledge and is not part of Recharge's standard turnkey solution.
  • This feature is not supported by Recharge as per the design and integration policy as it requires custom coding on your end.

Shopify Checkout integration

Add an item to the cart from outside of the product page with Ajax by specifying the variant_id, quantity, and selling_plan.

Step 1 - Add a listener

  1. Add a listener to the Add to cart link button.
  2. Within the listener, call the addItemToCart function, and specify parameters for:
  • variant_id
  • quantity
  • selling_plan

🚧

Note:

It is recommended that you run an Ajax cart/clear before calling the Ajax add-to-cart function.

Step 2 - Identify parameters

  1. Refer to Shopify's guide find a variant id to identify the variant_id.
  2. Locate the selling_plan.
    1. If the product only has one subscription interval option, you can use liquid code to get the first selling plan ID associated with the subscription: {{product.selling_plan_groups[0].selling_plans[0].id}}
    2. If a product has multiple interval options, you must loop through the selling_plan_groups and then the selling_plans parameter to get the relevant ID for the given interval option.
<input type="button" id="add-to-cart-button" value="ADD TO CART" onClick="addItemToCart(36807328039071, 1, {{product.selling_plan_groups[0].selling_plans[0].id}})">       
<script>  
function addItemToCart(variant_id, qty, selling_plan) {

    data = {
      "id": variant_id,
      "quantity": qty,
      "selling_plan": selling_plan
    }
    jQuery.ajax({
      type: 'POST',
      url: '/cart/add.js',
      data: data,
      dataType: 'json',
      success: function() { 
        window.location.href = '/cart'; 
      }
    });
  }
</script>    

Add a product from an external site

If you want to add a product from an external site, you still need to have a Shopify page that contains the Ajax code and performs a redirect to the cart page. You cannot call the Shopify Ajax code from an external site, it must be hosted on your Shopify site.


Need Help? Contact Us