Как добавить товар в корзину без перезагрузки страницы?

Так что я хочу добавить товар в корзину без перезагрузки страницы каждый раз, я использовал ajax в предыдущем проекте, и время отклика было не очень хорошим, так что есть ли лучший способ сделать это, который не будет медленным? Если да, то как мне это исправить? Также я не очень хорошо разбираюсь в javascript, так что если вы можете немного объяснить, я буду очень признателен за вашу помощь, спасибо!

ссылка на остальной основной код:

https://gist.github.com/StackingUser/34b682b6da9f918c29b85d6b09216352

шаблон:

{% load static %}

<link rel="stylesheet" href="{% static 'store/css/shop.css' %}" type="text/css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<script type="text/javascript">

    var user = '{{request.user}}'

    function getToken(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    const csrftoken = getToken('csrftoken');    

    function getCookie(name) {
        // Split cookie string and get all individual name=value pairs in an array
        var cookieArr = document.cookie.split(";");

        // Loop through the array elements
        for(var i = 0; i < cookieArr.length; i++) {
            var cookiePair = cookieArr[i].split("=");

            /* Removing whitespace at the beginning of the cookie name
            and compare it with the given string */
            if(name == cookiePair[0].trim()) {
                // Decode the cookie value and return
                return decodeURIComponent(cookiePair[1]);
            }
        }

        // Return null if not found
        return null;
    }
    var cart = JSON.parse(getCookie('cart'))

    if (cart == undefined){
        cart = {}
        console.log('Cart Created!')
        document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/"
    }
    console.log('Cart:', cart)

</script>

{% include 'main/includes/nav.html' %}

<section class="shop">

    <div class="wrap">

        {% 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 %}

    </div>
</section>

<script type="text/javascript" src="{% static 'store/js/cart.js' %}"></script>

{% include 'main/includes/footer.html' %}

попробуйте заменить тег <a> на другой тег, например <div>

Если это не сработает, попробуйте e.preventDefault()

<a onclick='(e) => e.preventDefault()' data-product="{{product.id}}" data-action="add" class="add-to-cart-action update-cart">Add to cart</a>

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