Как использовать ajax для обновления элементов корзины
Итак, пытаюсь использовать ajax для обновления {{cartItems}} на nav, когда кто-то нажимает кнопку add-to-cart на шаблоне без перезагрузки страницы, но не могу заставить ajax работать, занимаюсь этим уже довольно долго. буду очень признателен, если кто-то сможет помочь, thx!
views.py
def ajax_update(request):
data = cartData(request)
cartItems = data['cartItems']
context = {"cartItems": cartItems}
return render(request, 'store/shop.html', context)
urls.py
path('ajax_update/', views.ajax_update, name="ajax_update"),
cart.js
function addCookieItem(productId, action){
console.log('User is not authenticated')
if (action == 'add'){
if (cart[productId] == undefined){
cart[productId] = {'quantity':1}
}else{
cart[productId]['quantity'] += 1
}
}
if (action == 'remove'){
cart[productId]['quantity'] -= 1
if (cart[productId]['quantity'] <= 0){
console.log('Item should be deleted')
delete cart[productId];
}
}
console.log('CART:', cart)
document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/"
/*replacing location.reload() with ajax*/
function updating_cart_ajax(){
$.ajax({
headers:{
'Content-Type':'application/json',
'X-CSRFToken':csrftoken,
},
url: 'ajax_update/',
type: 'POST',
data : {
'cartItems' : cartItems,
},
success: function(data){
console.log('success')
console.log(csrftoken)
}
})
}
}
шаблон
{% for product in products %}
<div class="shop-card">
<a href="{{product.slug}}">
<div class="image-card-wrapper">
<img id="store-cart-img" src="{{ product.image_URL }}">
</div>
<div class="card-shop-info">
<p>{{product.name}}</p>
<p id="styleb">${{product.final_price | floatformat:2}} | <a data-product="{{product.id}}" data-action="add" class="add-to-cart-action update-cart">Add to cart</a></p>
</div>
</a>
</div>
{% endfor %}