0

I have 2 $.ajax() functions in one html rendered by Django. The first one works correctly, the second one answers with a 403 CSRF Failed: CSRF token missing or incorrect.

This is the relevant js code:

$(document).ready(function(){

   window.CSRF_TOKEN = "{{ csrf_token }}";

    ....
    $.ajax({
           method: "POST",
           url: "{% url 'alpha:create_cart_item' %}",
           data: {'item': stockitem_id, 'quantity': '1', 'csrfmiddlewaretoken': window.CSRF_TOKEN},
           success: function(resp){...}

    ....
    $.ajax({
           method: "PUT",
           url: "{% url 'alpha:update_cart_item' 0 %}".replace("0", cartitem_id),
           data: {'pk': cartitem_id, 'csrfmiddlewaretoken': window.CSRF_TOKEN},
           success: function(resp){
               panel_div.hide();
           },
           error: function(resp){
           }
       });

The second Ajax request is not working. I set the csrfmiddlewaretoken in the exact same way. Why am I getting the 403?. Obviously I'm missing something, please help.

UPDATE

Debugging this I found out that if I change the method o the 2nd request to "POST", it works correctly. But I do need the method to be "PUT".

Also, I'm using Django REST Framework...

Alejandro Veintimilla
  • 10,743
  • 23
  • 91
  • 180
  • This happens to work if **both** methods are POST? Sounds weird but try not using `window.CSRF_TOKEN` but the example Django used. [this is an answer telling you the way](http://stackoverflow.com/a/29666766/1105249), although using `$.cookie` from the jquery cookie plugin would work the same. Try and see if getting it from cookies, instead of window, works. Perhaps it changes among requests when different methods or something alike. – Luis Masuelli Sep 16 '16 at 13:34
  • 1
    btw *do not remove the {% csrftoken %} tag in your template if you used it*, or the cookie will not be populated with the value. An alternative is to wrap your view with `ensure_csrf_cookie` if you do not plan to include the token in a template but you still need the cookie. But with my suggestion you will be getting the value *directly from the cookie*, as the django docs suggest. – Luis Masuelli Sep 16 '16 at 13:36

0 Answers0