How to resolve add.js 404 error in custom script?

How to resolve add.js 404 error in custom script?

ijw
Shopify Partner
11 0 2

I am running into this common issue and am completely stumped. 

 

Here is the button I'm testing: 

<input type="button" id="add-to-cart-button" value="ADD TO CART" onClick="addItemToCart({{ product.id }})">

 

Here is the script I have in my custom js file (I have moved this around and get the same result)

  function addItemToCart(prodid) {

    console.log(prodid);

    let formData = {
       'items': [{
        'id': prodid,
        'quantity': 1
        }]
      };

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

  }

 

And I add this to the theme.liquid file

  {{ 'api.jquery.js' | shopify_asset_url | script_tag }}

 

The console outputs the correct Product ID (no variants are in use). 

But the 404 Error persists with the same references:

e.fetch	@	shop_events_listener…b43d5a7887c1d4.js:1
addItemToCart	@	custom.min.js?v=1115734…:1
onclick	@	add-ons:1221

 

The ultimate goal is to add to cart without leaving the page and then update the cart after this finishes. 

Any help is greatly appreciated from the community. (Please no offers for paid assistance)

 

Reply 1 (1)

Cristian_Matos
Shopify Partner
5 0 2

/cart/add.js returns a 404 error when the variant ID doesn't exist. I suggest double checking that you are sending a valid variant ID.