[Answered ]-Django Ajax Request still results to CSRF Token Missing or Incorrect

2👍

Add the below code in the script. This will send the csrf token in the request in each ajax request

1. This will allow to get csrf token

// using jQuery
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');

2. This will send csrf token on every ajax request

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

3.Now send your ajax request

$.ajax({
    url: window.location.href,
    type: 'POST',
    data: data,
    success: function(result) {
      console.log(result);
    },
});

For more information visit django official documentation

Leave a comment