Reputation: 39
Problem I want to add the product to the cart using ajax so that the page is not reloaded or refreshed and a popup is shown that the product is added to the cart.
Script
$(document).on("click",".Id_submit",function(event){
event.preventDefault();
var selector = $(this).closest(".productID")
console.log(selector.find("form").attr('action'))
$.ajax({
type : 'POST',
url: selector.find("form").attr('action'),
success: function()
{
alert("Product added to cart")
}
});
html
<form id='transactionIDValue' class="d-inline" method="post">
{{cart_product_form}}
{% csrf_token %}
<input type="submit" class="btn btn-primary shadow px-5 py-2 Id_submit" value="Add To Cart">
</form>
views.py
@require_POST
def cart_add(request, product_id):
cart = Cart(request)
product = get_object_or_404(transactions, id=product_id)
form = CartAddProductForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
cart.add(product=product, quantity=cd['quantity'])
print(cart)
# request.session['items_total'] = cart.product.count()
return HttpResponse('success')
urls.py
extra_patterns = [
path('add/carts/<int:product_id>/', views.cart_add, name='cart_add'),
]
urlpatterns=[
path ('add/',include(extra_patterns)),
]
Error
This is the errror I'm facing Forbidden (CSRF token missing or incorrect.): /cart/add/add/carts/16/
The issue I'm facing is that using the script it goes the cart url but the product is not added and in the console it shows that the url is forbidden. So, can someone help me with this issue please.
Upvotes: 0
Views: 1796
Reputation: 767
There are a couple of ways of doing this.
A lot of people will recommend just adding the decorator @csrf_exempt
to the view like:
@require_POST
@csrf_exempt
def cart_add(request, product_id):
...
See here on why this is a bad idea generally, but you can draw your own conclusions in how you want to protect your app.
The best thing to do is to submit the csrf_token field value with the js:
$(document).on("click",".Id_submit",function(event){
event.preventDefault();
var selector = $(this).closest(".productID")
console.log(selector.find("form").attr('action'))
const form_data = {
csrfmiddlewaretoken: $('#transactionIDValue input[name="csrfmiddlewaretoken"]').val()
}
$.ajax({
type : 'POST',
url: selector.find("form").attr('action'),
data: form_data,
success: function()
{
alert("Product added to cart")
}
});
Upvotes: 1