Add Products To Cart By Clicking Checkout

Hi community!

I’m trying to implement a functionality in the cart of my site and I can’t get it to work 100%.

It consists in that if the user marks (or not) some radio buttons, some products are added to the cart after clicking on the checkout button. They are two radio buttons with two different products. The problem is that sometimes it adds only one, sometimes neither, and sometimes both, but it is not consistent in its operation.

The function I am using to add the product to the cart is this:

function agregarProductoAlCarrito(variant_id){ 
      let data = {
        'items':[{
          'id': variant_id,
          'quantity': 1
        }]
      };
    
      fetch('/cart/add.js', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      })
      .then(response => {
        return response.json();
      })
      .catch((error) => {
        console.error('Error:', error);
      });
    }

To remove the product (if it is already in the cart):

function eliminarProductoDelCarrito(variant_id){
    let data = {
      'items':[{
        'id': variant_id,
        'quantity': 0
      }]
    };

    fetch('/cart/change.js', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    })
    .then(response => {
      return response.json();
    })
    .catch((error) => {
      console.error('Error:', error);
    });
  }

Then on the onclick of the checkout button I do the following:

$(".custom-btn-checkout").click( function(e){
          e.preventDefault();
            if(radio1Si.checked){
              agregarProductoAlCarrito({{ variant1_id }});
            }

            if(radio1No.checked){
              eliminarProductoDelCarrito({{ variant1_id }});
            }

            if(radio2Si.checked){
              agregarProductoAlCarrito({{variant2_id }});
            }

            if(radio2No.checked){	
              eliminarProductoDelCarrito({{ variant2_id }});
            }
              $(this).submit();
            
          }  
    });

Could someone give me an idea of what might be going on? Perhaps it is something related to the execution time of the add and remove functions. I tried adding setTimeout to them but it doesn’t finish working 100%.

I would really appreciate if someone can give me some help.

Thanks!

Hi @ghuerta ,

When you run the ajax cart function, it will take time to process, so some cart.js cases have not been processed yet run the submit form function. So you should run it in a process. You need to add ‘check’ variable to check when add to cart is complete and run submit function inside ajax.

You can refer to Dawn theme to see how to run ajax cart in progress: https://github.com/Shopify/dawn/blob/main/assets/product-form.js

Hope it helps!

2 Likes

Thank you for the reply, @LitExtension !

I have almost solved the problem, except for one small detail.

I need that when the cart page is loaded, two products are automatically removed from the cart, to avoid that these that I added previously are not added twice, since they are products that must be added only once.

I tried the following function, executing it inside the onReady() but it didn’t work:

function removeProductsFromCart(id1, id2){ 
      let data = {
        'items':[
          {
            'id': id1,
            'quantity': 0
          },
          {
          	'id': id2,
            'quantity': 0
          }
          
        ]
      };
    
      fetch('/cart/change.js', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      })
      .then(response => { 
         return response.json();
      })
      .catch((error) => {
        console.error('Error:', error);
      }); 
    }

I also tried to execute it inside the onClick() of the checkout button, but something similar to what happened before with the add functions happens.

Any suggestion?

Thanks again!

Hi @ghuerta ,

First, you need to check 2 products already in your cart to run this function.

And with your function, I found just calling it and passing the correct ID everything works fine.

Please send me the site and product link, I will debug it for you.

If my previous tutorial can help you, please mark it as a solution. Thank you and good luck.

1 Like