[Fixed]-Django Ajax "FORBIDDEN" error

20👍

You need a CSRF token even if the request is to the same domain. There’s code here to add a CSRF token to your AJAX requests (with jQuery):

https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#ajax

This link points to version 1.7, if you are using a different version of Django you can select your version from the floater menu on the bottom right.

9👍

You will get 403 errors if you have csrf on, try adding in views.py to see if this is causing it:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
view class/method

1👍

Well, if you still want CSRF protection, read my solution.

In my case I have a template in which I don’t want to have a <form></form> element. But I still want to make AJAX POST requests using jQuery.

I got 403 errors, due to CSRF cookie being null, even if I followed the django docs (https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/). The solution is in the same page, mentioning the ensure_csrf_cookie decorator.

My CSRF cookie did get set when I added this at the top of my views.py:

from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie

Also, please note that in this case you do not need the DOM element in your markup / template: {% csrf_token %}

1👍

Download jQuery.Cookie and include it, from here: http://plugins.jquery.com/cookie/

Then, add beforeSend function and send csrf token like this:

jQuery.ajax({
    type: "POST",
    dataType: "json",
    data: dataString,
    beforeSend: function(xhr, settings) {
        xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
    },
    success: function(json) {
          jQuery(".signup").attr('disabled', false);
          $('.success').show();
          console.log(json.message);
    },
    error: function(jqXHR, textStatus, errorThrown) {
          jQuery(".signup").attr('disabled', false);
          $('.fail').show().append(errorThrown);
          console.log(textStatus);
    }

});

Leave a comment