Opened 5 years ago

Closed 5 years ago

#30641 closed Cleanup/optimization (wontfix)

Update docs for using CSRF with Ajax.

Reported by: JeroenvO Owned by: nobody
Component: Documentation Version: dev
Severity: Normal Keywords: csrf token jquery context templatetag ajax
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Docs state: (https://docs.djangoproject.com/en/2.2/ref/csrf/)
In order to get CSRF token in Javascript, for instance for an AJAX request.

{% csrf_token %}
<script type="text/javascript">
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
</script>

but since {{ csrf_token }} is available in the context, a much cleaner version would be:

<script type="text/javascript">
// using jQuery
var csrftoken = '{{ csrf_token }}';
</script>

Change History (1)

comment:1 by Mariusz Felisiak, 5 years ago

Component: CSRFDocumentation
Resolution: wontfix
Status: newclosed
Summary: Update docs for using CSRF with AjaxUpdate docs for using CSRF with Ajax.
Version: 2.2master

Thanks for the report, but I believe that the current recommendation is better because it works if:

<script type="text/javascript">
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
</script>

is a part of external JavaScript file (see extensive discussion in PR).

Note: See TracTickets for help on using tickets.
Back to Top