Currently, I am working on implementing an add to cart feature and I would like the new cart total to be displayed after adding a product without the need to reload the page. At the moment, the page reloads to show the changes in the cart after a product has been added.
(SOME OF THE CODE MAY BE IN DANISH, HOPE THAT'S OKAY)
HTML (The add to cart button)
<div class="buy-item flex flex-ai-c">
<button data-product="{{product.id}}" data-action="add" class="add-button add-btn update-cart">TILFØJ TIL KURV</button>
<div class="flex flex-ai-c flex-jc-c">
<span class="cart-quantity-text">ANTAL</span>
<input class="cart-quantity-input" type="number" value="1">
</div>
</div>
JS
function addCookieItem(productId, action) {
if(action == 'add'){
if(cart[productId] == undefined){
cart[productId] = {'quantity':parseInt(antal.value)}
}else{
cart[productId]['quantity'] += parseInt(antal.value)
}
}
if(action == 'add-from-cart'){
cart[productId]['quantity'] += 1
}
if(action == 'remove-from-cart'){
cart[productId]['quantity'] -= 1
if(cart[productId]['quantity'] <= 0){
console.log('Remove Item')
delete cart[productId]
}
}
if(action == 'delete'){
delete cart[productId]
}
console.log('Cart:', cart)
document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/"
location.reload()
}
Django
def cookieCart(request):
try:
cart = json.loads(request.COOKIES['cart'])
except:
cart = {}
print('Cart:', cart)
items = []
order = {'get_cart_total':0, 'get_cart_items':0}
cartItems = order['get_cart_items']
for i in cart:
try:
cartItems += cart[i]['quantity']
product = Product.objects.get(id=i)
total = (product.price * cart[i]['quantity'])
order['get_cart_total'] += total
order['get_cart_items'] += cart[i]['quantity']
item = {
'product':{
'id':product.id,
'name':product.name,
'price':product.price,
'imageURL': product.imageURL,
'stripe-price': product.stripe_price_id,
'description': product.description,
'vare_nr': product.vare_nr,
},
'quantity': cart[i]['quantity'],
'get_total': total
}
items.append(item)
except:
pass
return {'cartItems': cartItems, 'order': order, 'items':items}
def cartData(request):
cookieData = cookieCart(request)
cartItems = cookieData['cartItems']
order = cookieData['order']
items = cookieData['items']
return {'cartItems': cartItems, 'order': order, 'items':items}