[Fixed]-Passing csrf token through $.ajax() data not working

1👍

You have to use {% csrf_token %} inside your <form>; it will render a hidden input, which has a name and a value. Then, in the ajax’s data, you should send that input’s value, like this:

...
data: {
    text: $('.comment_text').val(),
    csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(),
},
...

0👍

I believe your headers need to look like this:

headers: {
  'X-CSRFToken': "{{ csrf_token }}"
}

Also, in your form, you should use {% csrf_token %} rather than {{ csrf_token }}

Check out the docs for info about this. https://docs.djangoproject.com/en/1.10/ref/csrf/#ajax

Leave a comment