How can i add a Shopify product to the cart via AJAX API?

Highlighted
Shopify Partner
30 0 1

So i sell add on items on my store in addition to my main products. When the customer selects an add on item in the product page i want to add that selected add on item to the cart through AJAX after Shopify adds the main product.

I know i'm going to have to make a call to ADD /cart/add.js and pass in the selected add on variantid. Whenever i make this call however, it never adds consistently...sometimes the add on item gets added successfully along with the main product, sometimes the add on item doesn't get added, and sometimes ONLY the add on item gets added and not the main item. I'm thinking my AJAX call to add to the cart is conflicting with Shopify adding the main product which is why sometimes my add on item gets added and NOT the main product. Is there a way to add an add on item to the cart that works consistently every time (where BOTH add on and main product get added & not one or the other)? am i missing something in my ajax request? this is my AJAX request:

 

 

  function ajax_checkout() {
            console.log("Adding now:");
            $.ajax({
                type: 'POST',
                async: false,
                url: '/cart/add.js?id=' + selected_variant_id,
                dataType: 'json',
                success: function (response) {
                    console.log("Added: (" + response.title + "), to Cart");
                }
            });
        };

 

 

 

For example see https://embrlabs.com/products/embr-wave

The above website sells extended warranty and when you select a warranty option the warranty gets added to the cart every time in addition to the main hardware product. I need to know how they are doing this. Anyone have any insight? Thank you!! 

0 Likes