Join us for an upcoming Shopify Partner webinar on February 27, 2024. Discover the latest Checkout Extensibility features, and deep dive on improvements to Shopify Functions and Web Pixels. Register now for either the 10am EST or 2pm EST sessions.

Error adding products to cart:

Saurabh__Sharma
Visitor
1 0 0

I am creating Quick order page to add product in wholesale in for shopify I am getting this error please check below.

Error adding products to cart: {"status":"bad_request","message":"expected String to be a id: id","description":"expected String to be a id: id"} addToCart @ quick-order:7564 await in addToCart (async) onclick @ quick-order:7434

My Code

 

<form id="quickOrderForm">
  <div id="orderRows">
  <div class="orderRow"><label for="productNameInput">Enter Product Name:</label> <input placeholder="Product Name" class="productNameInput" type="text"> <label for="quantityInput">Enter Quantity:</label> <input min="1" placeholder="Quantity" class="quantityInput" type="number"> <button type="button" onclick="removeRow(this)">Remove Row</button></div>
  </div>
  <button type="button" onclick="addRow()">Add Row</button> <button type="button" onclick="addToCart()">Add to Cart</button></form><script>
    async function getProductInfo(productName) {
      const storefrontToken = ''; // Replace with your actual Storefront API token
      const storefrontURL = ``;
 
      const query = `
        query {
          products(query: "${productName}", first: 1) {
            edges {
              node {
                id
                title
                variants(first: 1) {
                  edges {
                    node {
                      id
                      priceV2 {
                        amount
                        currencyCode
                      }
                    }
                  }
                }
              }
            }
          }
        }
      `;
 
      const response = await fetch(storefrontURL, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Shopify-Storefront-Access-Token': storefrontToken,
        },
        body: JSON.stringify({ query }),
      });
 
      const data = await response.json();
 
      if (data.errors) {
        throw new Error(data.errors[0].message);
      }
 
      return data.data.products.edges[0]?.node;
    }
 
    function addRow() {
      var orderRows = document.getElementById('orderRows');
      var newRow = document.createElement('div');
      newRow.classList.add('orderRow');
      newRow.innerHTML = `
        <label for="productNameInput">Enter Product Name:</label>
        <input type="text" class="productNameInput" placeholder="Product Name">
        <label for="quantityInput">Enter Quantity:</label>
        <input type="number" class="quantityInput" placeholder="Quantity" min="1">
        <button type="button" onclick="removeRow(this)">Remove Row</button>
      `;
      orderRows.appendChild(newRow);
    }
 
    function removeRow(button) {
      var orderRow = button.parentNode;
      orderRow.parentNode.removeChild(orderRow);
    }
 
    async function addToCart() {
      var items = [];
      var orderRows = document.getElementsByClassName('orderRow');
 
      for (var i = 0; i < orderRows.length; i++) {
        var productName = orderRows[i].querySelector('.productNameInput').value.trim();
        var quantity = orderRows[i].querySelector('.quantityInput').value.trim();
 
        if (productName && quantity && parseInt(quantity) > 0) {
          try {
            const productInfo = await getProductInfo(productName);
 
            if (productInfo) {
              const variantId = productInfo.variants.edges[0].node.id;
              items.push({
                id: variantId,
                quantity: parseInt(quantity)
              });
            } else {
              alert(`Product with name ${productName} not found.`);
              return;
            }
          } catch (error) {
            console.error('Error fetching product info:', error);
            alert(`An unexpected error occurred while fetching product info. Please try again.\nError details: ${error.message}`);
            return;
          }
        } else {
          alert('Please enter valid product name and quantity for each row.');
          return;
        }
      }
 
      if (items.length > 0) {
        const cartURL = '/cart/add.js';
 
        try {
          const response = await fetch(cartURL, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({ items }),
          });
 
          if (response.ok) {
            const data = await response.json();
            console.log(data); // Log the response for debugging
 
            if (data.status === 'created') {
              alert('Products added to cart!');
              // Clear the form after successful addition to cart
              clearForm();
              // Redirect to the cart page if needed
              // window.location.href = '/cart';
            } else {
              console.error('Error adding products to cart:', data);
              alert(`Error adding products to cart. Please try again.\nError details: ${JSON.stringify(data)}`);
            }
          } else {
            const errorMessage = await response.text();
            console.error('Error adding products to cart:', errorMessage);
            alert(`An unexpected error occurred. Please try again.\nError details: ${errorMessage}`);
          }
        } catch (error) {
          console.error('Error adding products to cart:', error);
          alert(`An unexpected error occurred. Please try again.\nError details: ${error.message}`);
        }
      } else {
        alert('Please enter at least one product name and quantity.');
      }
    }
 
    function clearForm() {
      document.getElementById('orderRows').innerHTML = '<div class="orderRow"><label for="productNameInput">Enter Product Name:</label><input type="text" class="productNameInput" placeholder="Product Name"><label for="quantityInput">Enter Quantity:</label><input type="number" class="quantityInput" placeholder="Quantity" min="1"><button type="button" onclick="removeRow(this)">Remove Row</button></div>';
    }
  </script>

 
Reply 1 (1)

Liam
Shopify Staff
2677 288 736

Hi Saurabh,


From the error message you've shared it sounds like the API is expecting a string format for the product or variant ID, but it's receiving something else, so you'll want to ensure that the variantId you are pushing into the items array is a string. In your addToCart function, you might want to explicitly convert the variant ID to a string when adding it to the items array.

 

You should also make sure that getProductInfo is returning a valid product variant ID. You can add a console.log statement to inspect the productInfo and variantId:

 

const productInfo = await getProductInfo(productName);
console.log('Product Info:', productInfo); // Add this line for debugging
if (productInfo) {
  const variantId = productInfo.variants.edges[0].node.id;
  console.log('Variant ID:', variantId); // Add this line for debugging
// ... rest of your code
}

Hope this helps!

Liam | Developer Advocate @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog