Create an "Add-to-cart" button on any page with AJAX

Overview

Creating your own add-to-cart button can open up many possibilities. You can create your own product display page, add a button on an informational page, or feature a product on the home page of your store.

This article will explain how to create an add-to-cart button anywhere in your BigCommerce store using AJAX. The code examples below are meant for instruction only. We highly recommend you tailor your code to your individual use case.

Below the full script, we've included an explanation that breaks down each step the code takes to add the subscription item to cart.

📘

Note

AJAX (Asynchronous JavaScript and XML) is a set of protocol that let you send and receive data client-side (in the browser). AJAX is what allows you call a server from the front end to get information, then do something with it based on user interaction. For more information on AJAX, see Mozilla's documentation.

Prerequisites

  • This tutorial assumes you're using the base Cornerstone theme. Apply the base Cornerstone theme to your store if you want to follow along.
  • Use this tutorial with a product page. If you use the below code on any other page, such as the home page or category page, the script will add the first product it can find on the page. You'll need to modify the script to work any other way than as described here.
  • Use this script with simple products i.e., product that do not have variants or modifiers.

1. Create HTML element

First, create the HTML element to which you will attach the onClick event that triggers the add-to-cart function. This element can be a simple button, as shown below.

<button class="button button--primary" id="testing" onclick="ajax_add_to_cart();"> ADD TO CART </button>

Add the line of HTML to your BigCommerce theme. See Editing Stencil theme files for details. Add the button to the product page template found in the theme files under templates > components > products > product-view.html. Add it below the productView-details product-options element as shown so the button appears below the product information.

The easiest way to do this is by using the built-in theme code editor within the Control Panel.

1658 1708

2. Embed add-to-cart script in BigCommerce store

Replace the store hash in the script with your store's hash, and add your store domain to the get_cart_details() function as noted below.

<script type="text/javascript" charset="utf-8">
let cartData;
var prodData = {};

function camelCaseKeysToUnderscore(obj) {
    if (typeof(obj) != "object") return obj;
    for (var oldName in obj) {
        newName = oldName.replace(/([A-Z])/g, function($1) {
            return "_" + $1.toLowerCase();
        });
        if (newName != oldName) {
            if (obj.hasOwnProperty(oldName)) {
                obj[newName] = obj[oldName];
                delete obj[oldName];
            }
        }
        if (typeof(obj[newName]) == "object") {
            obj[newName] = camelCaseKeysToUnderscore(obj[newName]);
        }
    }
    return obj;
}

function get_cart_details() {
    const isResponseOk = (response) => {
        if (!response.ok)
            throw new Error(response.status);
        return response.text()
    }
    fetch("/api/storefront/carts/") 
        .then(response => isResponseOk(response))
        .then(data => cartData = JSON.parse(data))
        .catch(err => console.log("this fails"))
}

function get_prod_data( ) {
    var ourData = RCA_DATA.RCA_PRODUCT_DATA.filter(v => v.id === parseInt(document.getElementsByName('product_id')[0].value));

    prodData.id = ourData[0].id;
    prodData.var_id = ourData[0].variants[0].id;
    prodData.subscriptions = ourData[0].subscriptions[0];
    prodData.isSubscription = true;
    prodData.frequency = ourData[0].subscriptions[0].order_interval_frequency_options[0];

    return prodData;
}

var refreshIntervalId;

function add_subscription_details(){
    clearInterval(refreshIntervalId);
    var newobj = camelCaseKeysToUnderscore(cartData);
    
    RCAInterface.subscription.addProductToSubscriptions(
        prodData.id,
        prodData.var_id,
        newobj[0],
        prodData.subscriptions,
        prodData.isSubscription,
        prodData.frequency
    )
    console.log("Product subscriptions added");
}

function add_prod_first() {
    fetch('/cart.php?action=add&product_id=' + prodData.id)
        .then(data => {
            get_cart_details();
            refreshIntervalId = setInterval(function() {
                if (cartData) {
                    add_subscription_details();
                } else {
                    console.log("Waiting for cart details!");
                }
        },300)})
        .catch(err => {
            console.error(err)
        })
}

function ajax_add_to_cart() {
    get_prod_data();

    if (prodData.isSubscription) {
        add_prod_first();
    }
}
</script>

3. Adding script to BigCommerce

There are three ways to add JavaScript to BigCommerce.

  • Wrap the code in a <script> tag and add it to your store using the Script Manager.
  • Place the script at the bottom of the product-view Stencil template file where you placed the HTML element from Step 1.
  • For advanced builds and optimized load times consider bundling JavaScript into the theme.

How it works

Retrieve Recharge product data

The first part of the code above creates variables to store data.

let cartData;
var prodData = {};

The script calls the function ajax_add_to_cart which triggers the entire process of adding a Recharge subscription product to the cart. This function first runs through the get_prod_data function. The get_prod_data function uses the Recharge CDN file to get the individual product's information based on the product_id HTML element. This element contains the product ID, and appears on BigCommerce pages that contain products. The code then pushes this data into the prodData variable with the relevant subscription information.

function get_prod_data( ) {
    var ourData = RCA_DATA.RCA_PRODUCT_DATA.filter(v => v.id === parseInt(document.getElementsByName('product_id')[0].value));

    prodData.id = ourData[0].id;
    prodData.var_id = ourData[0].variants[0].id;
    prodData.subscriptions = ourData[0].subscriptions[0];
    prodData.isSubscription = true;
    prodData.frequency =  ourData[0].subscriptions[0].order_interval_frequency_options[0];
    return prodData;
}

Provided prodData.isSubscription is true, the script moves on to the next function.

Create BigCommerce cart with Recharge product

A BigCommerce cart with the item must already exist before the cart item can become a Recharge subscription product. The code uses the BigCommerce storefront add-to-cart URLs to create a cart.

function add_prod_first() {
    fetch('/cart.php?action=add&product_id=' + prodData.id)
        .then(data => {
            get_cart_details();
            refreshIntervalId = setInterval(function() {
                if (cartData) {
                    add_subscription_details();
                } else {
                    console.log("Waiting for cart details!");
                }
        },300)})
        .catch(err => {
            console.error(err)
        })
}

Note the correct product ID is appended to the URL from prodData.id, which was stored in the previous step.

Next, the code sets an interval to periodically check the BigCommerce cart until the product is successfully added. Then it executes the get_cart_details function.

function get_cart_details() {
    const isResponseOk = (response) => {
        if (!response.ok)
            throw new Error(response.status);
        return response.text()
    }
    fetch("/api/storefront/carts/") 
        .then(response => isResponseOk(response))
        .then(data => cartData = JSON.parse(data))
        .catch(err => console.log("this fails"))
}

This section retrieves the newly created cart data using the BigCommerce Storefront API and stores it in the cartData variable.

The code then moves to the final step, executing the add_subscription_details function.

Parse cart details to snake case and create Recharge subscription

The script contains a standalone function, camelCaseKeysToUnderscore.

function camelCaseKeysToUnderscore(obj) {
    if (typeof(obj) != "object") return obj;
    for (var oldName in obj) {
        newName = oldName.replace(/([A-Z])/g, function($1) {
            return "_" + $1.toLowerCase();
        });
        if (newName != oldName) {
            if (obj.hasOwnProperty(oldName)) {
                obj[newName] = obj[oldName];
                delete obj[oldName];
            }
        }
        if (typeof(obj[newName]) == "object") {
            obj[newName] = camelCaseKeysToUnderscore(obj[newName]);
        }
    }
    return obj;
}

This function takes in BigCommerce Cart data and translates it to snake case. Below, you see it takes the cartData as an argument to sanitize the product data into the format Recharge uses. Then the function combines it with the Recharge data.

function add_subscription_details(){
    clearInterval(refreshIntervalId);
    var newobj = camelCaseKeysToUnderscore(cartData);
    
    RCAInterface.subscription.addProductToSubscriptions(
        prodData.id,
        prodData.var_id,
        newobj[0], 
        prodData.subscriptions,
        prodData.isSubscription,
        prodData.frequency
    )
    console.log("Product subscriptions added");
}

Finally, the code executes the function RCAInterface.subscription.addProductToSubscriptions. As previously stated, this function is stored in the Recharge CDN and is available in all BigCommerce stores. It takes the Recharge subscription information and BigCommerce cart data as an argument.

It is important to note that the sequences explained above occur in a matter of milliseconds. Customers should then be able to proceed to checkout with the subscription product.

🚧

Note

Customizations contained in these guides are outside of our scope of Recharge support. We recommend you work with a developer to implement any advanced functionality.


Need Help? Contact Us