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.
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
         }
})
                        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.
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);
        }
    }
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With