I am having problem for ajax posts to my django ecommerce site after user login. The failing scenario is as follows:
1-) User comes to site and adds products to shopping cart without any problem. Adding product to cart is an ajax call and the code is as follows:
function addItemToCart(item_pk, quantity) {
var item_quantity;
if (!quantity) {
item_quantity = 1;
} else {
item_quantity = quantity;
}
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('Csrf-Token', csrftoken);
}
});
$.ajax({
type: 'POST',
url: '/api/cart/add-item/',
data: {
item: item_pk,
quantity: item_quantity
}
success: function(data, textStatus, jQxhr) {
updateCart();
},
error: function(jqXhr, textStatus, errorThrown) {
console.log(jqXhr, textStatus, errorThrown);
}
});
}
The above code works perfectly and user can add several products to the cart.
2-) After that the user logs in to the site to make the payment, but before he make the payment he wanted to add another product to the cart, but the code fails.
3-) The error message is as follows: "CSRF Failed: CSRF token missing or incorrect."
When I checked the request I see that the ajax call already set the csrf token. The only thing I figured out is that django has refreshed the token after user login. But I also make sure that ajax call has been set csrf header with the new one.
So, I am confused why it works before user login and it does not work after user login. Because both posts has been made with the correct csrf tokens.
Any idea about what am i missing?