Django csrf in JQuery's ajax for POST and DELETE



After wasting sometime looking to do AJAX with django and getting 403 due to csrf_token I found a solution that I hope will work for you.

Case1: POST method.


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) {
            console.log('csrf: '+csrftoken)
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});


$.ajax({
        method:'post',
        data: {'id': $(this).attr('group-id'), 'csrfmiddlewaretoken': '{{csrf_token}}'},
        beforeSend: function(xhr, settings) {
            if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                // Only send the token to relative URLs i.e. locally.
                xhr.setRequestHeader("X-CSRFToken",
                                     $("#csrfmiddlewaretoken").val());
            }
        }


    });

Case2: DELETE method

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}


    $(".group-delete").click(function(){
        alert($(this).attr('group-id'))
        $.ajax({
            url: 'group',
            method:'delete',
            data: {'id': $(this).attr('group-id'), 'csrfmiddlewaretoken': '{{csrf_token}}'},
            beforeSend: function(xhr) {
                xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
            }

        });//ajax
    });//click



sources:
https://stackoverflow.com/questions/13089613/ajax-csrf-and-delete
https://docs.djangoproject.com/en/2.0/ref/csrf/#setting-the-token-on-the-ajax-request
https://www.w3schools.com/js/js_cookies.asp

Comments

Popular Posts