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>