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.

Gonzalo Dambra
  • 891
  • 2
  • 19
  • 34

3 Answers3

8

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
         }
})
T.melz
  • 131
  • 1
  • 2
  • 9
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.

Carl Brubaker
  • 1,602
  • 11
  • 26
  • Where exactly I have to put ""if request.is_ajax()"", I already have "if request.method == POST"? – Lord-shiv Sep 13 '21 at 14:22
  • @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. – Carl Brubaker Sep 13 '21 at 18:53
2

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);
        }
    }
});
Gonzalo Dambra
  • 891
  • 2
  • 19
  • 34