Reputation: 11523
I'm wondering if I'm doing it correctly and if it is safe. Usually I send the csrf token on an AJAX request using Jquery like this:
$.ajax({
method: "POST",
...
data: {...'csrfmiddlewaretoken': '{{csrf_token}}'},
});
It works, but the documentation doesn't say anything about doing something like this. What is the difference between this and doing what the documentation recommends (getting the cookie and setting in on the header)?.
Upvotes: 2
Views: 507
Reputation: 1518
Disadvantages of using context variable over header are:
csrfmiddlewaretoken
in data
Django docs provide you with copy-paste js code, you can include in your scripts at project level and forget about csrfmiddlewaretoken
Upvotes: 1
Reputation: 308809
The advantage of reading the value from the cookie then setting the header, is that it is less repetitive. It also works if your ajax request is in a static javascript file (if it's not a Django template then you can't use {{ csrf_token }}
)
However, if you are happy adding the csrf token to the data of each ajax post request, that is fine, there is no problem doing it that way.
Upvotes: 1