Answer the question
In order to leave comments, you need to log in
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);
});
});
<...>
<!-- КОРЗИНА в шапке сайта -->
{% 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
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);
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 questionAsk a Question
731 491 924 answers to any question