[Fixed]-Csrf_token not found django ajax

1👍

Try to make the request this way

$.ajax({
        type:form.attr('method'),
        url:form.attr('action'),
        data:form.serialize(),
        success: function(){
          ...
        }
      });
👤Jaime

0👍

According to the Laravel Docs you should add CSRF Tokens in Ajax Requests like this:

HTML Code:

<meta name="csrf-token" content="{{ csrf_token() }}">

JS Code:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

In case of Django – You need to add the {% csrf_token %} template
tag as a child of the form element in your Django template. See this –
Question

Hope this helps!

0👍

You are calling $.post incorrectly. If you look at the request in your developer tools, I think you’ll see that the post data is empty.

The second argument should be the request data, and third argument is the success callback.

$.post("/post/",
       data,
       function (response_data) {
         alert("posted");
       }
);

Once you’ve fixed that, the Django docs show how to include the CSRF token as a header in ajax requests, so you don’t have to include it in the form body.

Leave a comment