Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forbidden (CSRF token missing or incorrect.):

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)
                        {
                        }
                    });
like image 321
ankit Avatar asked Mar 29 '16 17:03

ankit


1 Answers

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.

like image 57
xyres Avatar answered Oct 30 '22 09:10

xyres