Django: How to send csrf_token with Ajax
Asked Answered
P

3

9

I have my Ajax in a jQuery function:

btnApplyConfig.js:

$(".btnApplyConfig").click(function(){
    var token = $("input[name=csrfmiddlewaretoken]").val();
    // Some other vars I'm sending properly
    console.log('token: '+token); //printing correctly
    $("#"+frm).submit(function(e){
        e.preventDefault();
        console.log('Post method via ajax');
        $.ajax({
            url: '/ajax/validate_config',
            type: 'POST',
            data: {
                'token': token,
                //and other stuff I'm sending properly
            },
            dataType: 'json',
        });
    });
});

my Django view:

def validate_config(request):
    token = request.GET.get('token', None)
    #some other vars I've sent ok with ajax
    data = {
        #some vars
        'token': token,
    }
    if request.method == 'POST':
        item = MyClass.objects.filter(my_keyword=my_filter_values).update(my_ajax_values)
    return JsonResponse(data)

All the data is being processed properly, the only problem for me is that I'm getting the following error:

Forbidden (CSRF token missing or incorrect.): /ajax/validate_config/

I've put some prints in view in order to check if vars are being sent properly, and yes they are. How could I handle it? I checked some tutorials but I couldn't find a solution so far.

Pinkston answered 22/2, 2019 at 22:6 Comment(2)
Token needs to be sent in a X-CSRFToken header.Placatory
ajax csrfAalii
P
3

This was the solution that worked for me in this case:

Added this code before the Ajax code:

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});
Pinkston answered 23/2, 2019 at 12:50 Comment(0)
D
10

A very simpler way

let cookie = document.cookie
let csrfToken = cookie.substring(cookie.indexOf('=') + 1)

$.ajax({
         url: 'url/path',
         type: 'POST',
         headers: {
           'X-CSRFToken': csrfToken
         }
})
Denizen answered 30/12, 2020 at 14:27 Comment(1)
I can use it with JSON type and content type :) thanks, so simpleVickeyvicki
A
4

You can use this. You don't have to put anything in your view for it. It will automatically find it.

$.ajax({
  url: ,
  type: "POST",
  data: {
    'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
    // plus other data
  },
  dataType: 'json',
  success: ,
});

You probably also want to add if request.is_ajax() to your view.

Awestricken answered 23/2, 2019 at 6:22 Comment(2)
Where exactly I have to put ""if request.is_ajax()"", I already have "if request.method == POST"?Candra
@Lord-shiv if request.method == "POST" and request.is_ajax():. request.is_ajax() will prevent it from running the code if it isn't an AJAX request.Awestricken
P
3

This was the solution that worked for me in this case:

Added this code before the Ajax code:

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});
Pinkston answered 23/2, 2019 at 12:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.