Search code examples
ajaxdjangocsrf-token

Django: How to send csrf_token with Ajax


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.


Solution

  • 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);
            }
        }
    });