0
<script>
    function post(e) {
        data = $("#form_add_post").serialize();
        $.post( "/post/", function( data ) {
                alert("posted");
        });
        return false;
    }
    function addPost(){
    $(".matter").html("<form id='form_add_post' onsubmit='return post(event);'>{% csrf_token %} <table> <tr> <td class='heading'>Title: </td> <td class='box'><input type='text' name='title'></td> </tr> <tr> <td colspan='2'><textarea class='data' name='content'></textarea></td> </tr> </table> <input id='submitt1' type='submit'> </form>");
}
</script>

I am trying to perform a AJAX post call. I have placed the csrf_token too. I have cross checked the data that is being sent. It is showing the entire details including the csrf_token.
My data:

csrfmiddlewaretoken=foYqu9LrR25AomOmcFkaEicmN3CU2wcRNVg1gRPgl2F9XfL6IWerpbSK6TUKd4Ke&title=Tester&content=hhgj%3B%3Bhghjbjn

But i am getting a 403 error showing

CSRF verification failed. Request aborted.

Image showing the error

dharmista
  • 103
  • 1
  • 2
  • 7
  • Take a look at this link [https://docs.djangoproject.com/es/1.10/ref/csrf/#ajax](https://docs.djangoproject.com/es/1.10/ref/csrf/#ajax) – Jaime Nov 15 '16 at 14:43

3 Answers3

1

Try to make the request this way

$.ajax({
        type:form.attr('method'),
        url:form.attr('action'),
        data:form.serialize(),
        success: function(){
          ...
        }
      });
Jaime
  • 311
  • 2
  • 12
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!

Community
  • 1
  • 1
Saumya Rastogi
  • 13,159
  • 5
  • 42
  • 45
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.

Alasdair
  • 298,606
  • 55
  • 578
  • 516