My django application uses ajax to add an item to shopping cart. The ajax request method is POST, and i enable request header via js:
var csrftoken = getCookie('csrftoken');
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
The problem is, that i send request not from the form, but just using a button and onClick event, so i do not use a {{ csrf }} in the template. So, the cookie is not set, until i visit another page (for example, login page). Should i use a form (it is not a very good idea, because i have many items on one page, and form with csrf token is created for each one), or there is a way to set csrf cookie manually, if it is not set? Thanks.