Add additional product to cart on add to cart button click

Rivky
New Member
1 0 0

Hi,

We would like to offer our customers and imprinting option on certain products.

We will be putting a checkbox on the product page and if it is checked, we want to add the imprinting product to the cart using the ajax api. This needs to happen on the add cart button click.

Below is my code. The issue is that it sometimes works and sometimes not. Whenever I test it, sometimes only the original product makes it to the cart, sometimes only the imprinting product makes it to the cart, and sometimes they both get there.

When I watch my requests in the network tab in chrome dev tool, I always see 2 cart/add requests being sent, and they always come back with a status of 200. Yet not always does the cart get updated with both products.

Here's my code. I added the onclick handler on the button and created the function in a script tag.

<button type="submit" onclick="addImprinting(document.getElementById('product-template-6217626419397-quantity').value)" class="product-form__add-button button button--primary" data-action="add-to-cart">{{ 'product.form.add_to_cart' | t }}</button>

<script type="text/javascript"> 
        const addImprinting=(qty)=>{
            const data = {
                quantity: Number(qty),
                id: 39290405519557
            };
           const xhr = new XMLHttpRequest();
           xhr.open('POST', '/cart/add.js', true);
           xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
           xhr.send(JSON.stringify(data)); 
        }
    </script>

 

Thanks for you help.

0 Likes