'How to make add to cart without reloading the page (js and django)?
Im making this add to cart functionality, and I want to show the new cart total after adding to cart without reloading the page. Right now I have it to reload the page to show the cart changes after having added a product.
(SOME OF THE CODE CAN BE IN DANISH, I HOPE ITS FINE)
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}
Solution 1:[1]
You can solve it with (very) different approaches:
- using an Ajax call (XMLHttpRequest) with vanilla javascript code
- using HTMX - quite new and less traditional way to boost your templating capabilities without writing JS code.
- using a JS Frontend framework/library (React, Vue, Angular, Svelte, etc..)
there are other methods offcourse but i think that for Django, those will be the main ones and the most documented solutions.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
