Ecommerce Shopify WordPress Discussion

Bad fetch request (400) with Shopify, removing item from cart using /cart/change.js

UPDATED WITH WORKING LINK I am new to javascript as well as using a site like stackoverflow. If I am missing any info or can make it easier to help in someway just let me know. Really banging my head on this one. I made a custom Shopify them for my store, and am attempting to make a custom cart drawer using ajax to add and remove products. The drawer itself, and adding products works, but I can't figure out removing products from the cart with ajax. Everything I do gets a Bad Request 400 error. Keep in mind the attempt in my code might be way off, or missing something very simple - either way I cannot figure it out and would appreciate any guidance. here is the link: if you click a product on the front page, and add it to cart, the cart drawer will pop out and add the product. JS and HTML are below. // Open / Close Cart Bullshit const openBtn = document.getElementById('open_cart_btn') const cart = document.getElementById('sidecart') const closeBtn = document.getElementById('close_btn') const backdrop = document.querySelector('.backdrop') openBtn.addEventListener('click', openCart) closeBtn.addEventListener('click', closeCart) backdrop.addEventListener('click', closeCart) // Open Cart function openCart(){ cart.classList.add('open') backdrop.classList.add('show') } // Close Cart function closeCart(){ cart.classList.remove('open') backdrop.classList.remove('show') } // Event delegation for the close button document.querySelector('.cart_content').addEventListener('click', function (event) { const closeBtn ='.close_btn'); if (closeBtn) { closeCart(); } }); async function updateCartDrawer() { const res = await fetch("/?section_id=cart-drawer"); const text = await res.text(); const html = document.createElement('div'); html.innerHTML = text; const newCartContent = html.querySelector(".cart_content"); const cartContent = document.querySelector(".cart_content"); if (cartContent && newCartContent) { cartContent.innerHTML = newCartContent.innerHTML; } } const addToCartForms = document.querySelectorAll('form[action="/cart/add"]'); addToCartForms.forEach((form) => { form.addEventListener("submit", async (event) => { //Prevent Normal Submission event.preventDefault(); //Submit form with AJax await fetch("/cart/add", { method: "post", body: new FormData(form), }); // Update cart await updateCartDrawer(); // Open cart drawer when add to cart cart.classList.add('open') backdrop.classList.add('show') // Get new cart object const res = await fetch("/cart.json"); const updatedCart = await res.json(); // Update cart count document.querySelectorAll(".cart-count").forEach((el) => { el.textContent = updatedCart.item_count; }); }); }); // Remove Item document.querySelector('.cart_content').addEventListener('click', async function (event) { const removeItemBtn ='.remove_item'); if (removeItemBtn) { event.preventDefault(); const productId = removeItemBtn.getAttribute('data-product-id'); // Make an AJAX request to remove the item from the cart const response = await fetch("/cart/change.js", { method: "post", body: JSON.stringify({ productId }), // Send the product ID or relevant data headers: { 'Content-Type': 'application/json', }, }); if (response.ok) { // Item removed successfully, update the cart await updateCartDrawer(); } } }); <!-- Backdrop --> <div class="backdrop"></div> <!-- Side Cart --> <div id="sidecart" class="sidecart"> <div class="cart_content" id="cart_content"> <div class="cart_header"> <a href="/cart" class="header__icon-wrapper tap-area tdf_cart_icon" aria-label="Cart" data-no-instant=""> <svg focusable="false" width="20" height="18" class="icon icon--header-cart" viewBox="0 0 20 18"> <path d="M3 1h14l1 16H2L3 1z" fill="none" stroke="currentColor" stroke-width="2"></path> <path d="M7 4v0a3 3 0 003 3v0a3 3 0 003-3v0" fill="none" stroke="currentColor" stroke-width="2"></path> </svg> </a> <div class="header_title"> <h2> Cart </h2> <span style="margin-top:-55px;" id="items_sum" class="cart-link__bubble{% if cart.item_count > -1 %} cart-link__bubble--visible{% endif %}">{{ cart.item_count }}</span> </div> <span id="close_btn" class="close_btn"> × </span> </div> <div class="cart-counter" id="sidecart-counter"> $0 <progress class="colored" max="7500" value="{{ cart.total_price }}"></progress> $75 <br> {% if cart.items.size == 0 %}Add items to your cart to receive free shipping.{% endif %}{% if cart.items.size != 0 %}{% if cart.total_price >= 7500 %} You've got free shipping!{% elsif cart.total_price < 7500 %}You're only {{ 7500 | minus: cart.total_price | money }} away from free shipping.{% endif %}{% endif %} </div> {% if cart.item_count == 0 %} <p class="cart-empty"> Your cart is empty </p> {% else %} <!-- Cart Items --> <div class="cart_items"> {% form 'cart', cart %} {% for item in cart.items %} <div class="cart_item"> <a href="{{ item.url_to_remove }}"> <button class="remove_item" data-product-id="{{ }}"> <span> ×</span> </button> </a> <div class="item_img"> <img src="{{ item.image | img_url: '200x' }}" alt="{{ item.title }}"> </div> <div class="item_details"> <h3> {{ item.title }} </h3> <p> {{ item.final_line_price | money }} </p> {% comment %} <div class="qty"> <span>-</span> <strong>1</strong> <span>+</span> </div> {% endcomment %} </div> </div> {% endfor %} {% endform %} {% endif %} </div> <!-- Cart Actions --> <div class="cart_actions"> <div class="subtotal"> <p>SUBTOTAL:</p> <p> {{ cart.total_price | money }} </p> </div> <div class="discounts"> <p> Discounts applied at checkout</p> {% comment %} <p>{{ cart.total_discounts | money }} </p> {% endcomment %} </div> </div> <div id="cart-buttons"> <a href=""> <button> Keep Shopping </button> </a> <a href=""> <div class="lock"> <svg style="margin-top:-3px;" focusable="false" width="17" height="17" class="icon icon--lock" viewBox="0 0 17 17"> <path d="M2.5 7V15H14.5V7H2.5Z" stroke="currentColor" stroke-width="1.5" fill="none"></path> <path d="M5.5 4C5.5 2.34315 6.84315 1 8.5 1V1C10.1569 1 11.5 2.34315 11.5 4V7H5.5V4Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"></path> <circle cx="8.5" cy="11" r="0.5" stroke="currentColor"></circle> </svg> </div> Checkout </a> </div> </div> </div> I have tried using both fetch and axios to remove products from the cart using the /cart/change.js shopify endpoint.
To remove an item from the cart, you should use the variant ID and set the quantity to 0. @eddieveddarfan69 fetch(window.Shopify.routes.root + 'cart/update.js', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ updates: { 47172325736730: 0 } }), }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));

December 30, 2023

TurboCommerce make the better internet purchasing globaly

Turbo Multi-language Translator

Make the better internet purchasing globaly

Turbosify SEO Speed Booster

5.0 (7) Free plan available
Get better conversions by improving store loading speed Installed

Turbo Multi-language Chat - AI Customer service in one hand

TurboCommerce make the better internet purchasing globaly
Our products

The help you need, when you need it

App by Turbo Engine

3 apps • 5.0 average rating

Turbosify Speed Booster

5.0 (7)
Get better conversions by optimizing shopify store Google page speed Installed

Turbosify Translator for Wordpress Woocommerce

5.0 (74) Free Wordpress Woocommerce Plugin
Translate your wordpress website to multiple language within 1 click, no configuration needed, no No technical required

Grow your business here

Whether you want to sell products down the street or around the world, we have all the tools you need.