4👍
✅
What I do for getting a proper csrf solution in place is this:
include my {% csrf_token %}
in a place it makes sense.
var csrfToken = $('input[name="csrfmiddlewaretoken"]').val();
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: postData,
csrfmiddlewaretoken: csrfToken,
dataType: 'json',
success: function(data) { }
});
I have struggled to get this working:
var csrftoken = $.cookie('csrftoken');
$.ajaxSetup({
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
});
But so far the first solution has proven to be the one that works best.
Source:stackexchange.com