I am trying to automatically update and refresh my item total in my cart page when an item quantity is updated. I keep getting an a return of NaN. I also see a console log of price is undefined, but I don’t know how to solved this.
Script:
function updateCartItem(cartId, cartItemId, quantityToAdd, csrftoken, price) {
console.log('price:', price);
fetch(`/api/carts/${cartId}/items/${cartItemId}/`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
"X-CSRFToken": csrftoken,
},
body: JSON.stringify({
quantity: quantityToAdd,
}),
})
.then((response) => response.json())
.then((data) => {
console.log("Cart successfully updated:", data);
console.log("CART:", cartId)
fetch("/cart/")
.then((response) => response.text())
.then((html) => {
// update the cart items and total price on the page with the new cart data
const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
const itemsContainer = document.getElementById("cart-items");
const totalContainer = document.getElementById("cart-total");
if (itemsContainer) {
itemsContainer.innerHTML = doc.getElementById("cart-items").innerHTML;
}
if (totalContainer) {
totalContainer.textContent = doc.getElementById("cart-total").textContent;
}
const itemTotalContainer = document.getElementById(`item-total-${cartItemId}`);
console.log('itemTotalContainer:', itemTotalContainer);
if (itemTotalContainer) {
const quantity = parseInt(itemTotalContainer.dataset.quantity);
const newQuantity = quantity + quantityToAdd;
const newTotal = newQuantity * price;
itemTotalContainer.textContent = `£${newTotal.toFixed(2)}`;
itemTotalContainer.dataset.quantity = newQuantity;
}
})
.catch((error) => {
console.error(error);
});
updateItemQuantity(); // update the quantity values on the page after the cart has been updated
updateCartQuantity(); // update the total cart quantity on the page
});
}
Html:
<div class="cart--box__item" id="item-total-{{item.id}}" data-quantity="{{ item.quantity }}">£{{item.total}}</div>