I'm trying to use JavaScript's fetch library to make a form submission to my Django application. However no matter what I do it still complains about CSRF validation. my code fetch don't work
ajax
function myidLikeCom(params) {
$.ajax({
type: 'POST',
url: '{% url "boards:likeComment" %}',
data: {
postid: params,
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
action: 'post'
},
success: function (json) {
document.querySelector(`#myidLikeCom${params}`).innerText = "json['result']";
},
error: function (xhr, errmsg, err) {
}
});
}
fetch don't work
function myidLikeCom(params) {
let data= {
postid: params,
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
}
fetch('{% url "boards:likeComment" %}', {
method: 'POST',
body: data,
})
}
Please see Django documentation for how to pass the CSRF token using AJAX.
You need to pass the token in the appropriate header.
$.ajax({
type: 'POST',
url: '{% url "boards:likeComment" %}',
headers: {
'X-CSRFToken': $('input[name=csrfmiddlewaretoken]').val(),
'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'
},
data: {
postid: params,
action: 'post'
},
success: function (json) {
document.querySelector(`#myidLikeCom${params}`).innerText = "json['result']";
},
error: function (xhr, errmsg, err) {
}
});