Как обновить корзину с помощью AJAX

Я пытаюсь использовать ajax для обновления {{cartItems}} на nav, когда кто-то нажимает кнопку add-to-cart на shop.html без перезагрузки страницы, пока что это то, над чем я смог поработать. Так как мне заставить это работать? Также если у вас есть другие предложения, пожалуйста, дайте мне знать! Буду очень признателен за помощь, спасибо!!!

остальная часть важного кода находится здесь: https://gist.github.com/StackingUser/34b682b6da9f918c29b85d6b09216352

urls.py

path('ajax_update/', views.ajax_update, name="ajax_update"),

nav.html

<span class="bag-icon">
    {% url 'store:cart' as url %}
    <a id="icons-account" href="{% url 'store:cart' %}"><i class="fas fa-shopping-bag {% if request.path == url %}change{% endif %}"></i><a id="lil-icon-two">{{cartItems}}</a></a>
</span>

cart.js

var updateBtns = document.getElementsByClassName('update-cart')

for(var i=0; i < updateBtns.length; i++){
    updateBtns[i].addEventListener('click', function(){
        var productId = this.dataset.product
        var action = this.dataset.action
        console.log('productId:', productId, 'action:', action)

        console.log('USER:', user)

        if(user === 'AnonymousUser'){
            addCookieItem(productId, action)
        }else{
            updateUserOrder(productId, action)
        }
    })
}


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({
        url: 'ajax_update/',
        success: function (result) {
            $('.shop').reload(result)
        },
    });
    }
}


function updateUserOrder(productId, action){
    console.log('User is logged in, sending data..')

        var url = 'update_item/'

        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type':'application/json',
                'X-CSRFToken':csrftoken,
            },
            body: JSON.stringify({'productId': productId, 'action': action})
        })

        .then((response) => {
           return response.json();
        })

        .then((data) => {
            console.log('data:', data)
            location.reload()
            /*replacing location.reload() with ajax*/
        });

}
Вернуться на верх