9
votes

I am making ajax call like below:

var data_dict = {'user':{{ user.id }}, 'bookId':that.id, 'csrfmiddlewaretoken': '{{ csrf_token }}'};
    $.ajax({
        type: 'POST',
        url:"/issuebook",
        data:data_dict,
        processData: false,
        contentType: false,
        success:function(response)
        {
        }
    });

urls.py is:

urlpatterns = [
url(r'^$',views.checkLogin,name='checklogin'),
url(r'^mylibrary/(?P<pk>\d+)/(?P<user_name>[\w\-]+)$',login_required(views.MyLibrary.as_view()),name='mylibrary'),
url(r'^centrallibrary/(?P<pk>\d+)/(?P<user_name>[\w\-]+)$',login_required(views.CentralLibrary.as_view()),name='centrallibrary'),
url(r'^issuebook$',login_required(views.IssueBookView.as_view()),name='issuebook'), 

]

I am getting "Forbidden (CSRF token missing or incorrect.): /issuebook" error on ajax call.

The csrf token in ajax call is getting rendered as:

var data_dict = {'user':{{ user.id }}, 'bookId':that.id, 'csrfmiddlewaretoken':'fSSdu8dJ4FO6FvDz8eU5ISzOewRYyGbC'};
                    $.ajax({
                        type: 'POST',
                        url:"/issuebook",
                        data:data_dict,
                        contentType: false,
                        success:function(response)
                        {
                        }
                    });
1
You just passed the string '{{ csrf_token }}' as csrfmiddlewaretoken, and your ajax call can't match it with the relative one. Instead you can get the hash value of csrf token manually from your html in your call function. - kasravnd
Add the rendered HTML template in the question too. - v1k45
@v1k45 i have added the rendered {{ csrf_token }} in the edited question. Apart from this I am just rendering few string values in the template which is working fine - ankit
@v1k45 also I am not using any forms in the template. This ajax call is done on button click event - ankit
Try setting the X-CSRFToken request header to csrftoken, in ajax request. - Rohit Jain

1 Answers

8
votes

This error is caused by processData and contentType options in your ajax function. Removing these two options will fix the issue.

Explanation: The arguments must be sent to Django as urlencoded with Content-Type application/x-www-form-urlencoded. Whereas, if you set processData: false it won't encode the POST parmaters and contentType: false will send ajax POST request as text/plain.