D
D
Dev_nab2018-08-09 22:19:42
Django
Dev_nab, 2018-08-09 22:19:42

Django - How to add a product to cart (AJAX)?

CORRECTED THE QUESTION
I'm trying to make sure that when you click on "Add to cart" the counter of goods (in the cart) in the header of the site is updated automatically (without reloading the page).
I figured out the view, now the problem is only in JavaScript. There is no AJAX request to the server.

cart/static/js/ajax_add.js

$("#update").click(function() {
        $('#counter').html(function(i, val) {
            console.log(data)
            $.ajax({
                url: form.attr("action"),
                type: 'POST',
                data: data,
                cache: true,
                success: function() { alert('Request has returned') },

                error: function(){ console.log("error") }

            });
            return (+val+1);
        });
    });


HTML
<...>
<!-- КОРЗИНА в шапке сайта -->
{% with total_items=cart|length %}
    {% if cart|length > 0 %}
        <a href="{% url "cart:cart_detail" %}">
            КОРЗИНА
            ({{ total_items }})
         </a>
    {% else %}
         КОРЗИНА
         (<div id="counter">{{ total_items }}</div>)
     {% endif %}
{% endwith %}
<...>

<!-- Список товаров -->
{% for product in products %}
<...>
<!-- Кнопка добавления товара в корзину -->
    <form action="{% url "cart:cart_add" product.id %}" method="post">
        {{ cart_product_form }}
        {% csrf_token %}
        <input id="update" class="button add" type="submit" value="Добавить в корзину">
    </form>
{% endfor %}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim, 2018-08-10
@Dev_nab

on the success event: recalculate the number and do $("#counter").html(value);
or in the response from the handler we get the quantity and do it again $("#counter").html(return);

W
Web Dentist, 2018-08-09
@kgb_zor

No one will dig into your code, especially not like this. Your question looks more like a task.
Output data to the console, check traceback on the server and throw it here. The task is trivial, google it in the end.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question