When attempting an Ajax POST request to retrieve news articles, I have encountered a persistent 403 error despite including a csrftoken in the headers. After searching online and attempting various solutions without success, I am left wondering: why does this error persist?
$('#search-articles').on('submit', function(event) {
event.preventDefault();
document.getElementById("loading").style.display = "block";
document.getElementById("search-bar").style.display = "none";
document.getElementById("articles").style.display = "none";
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;
}
$.ajax({
url: "{% url 'stocks_sites:get_news_articles' %}",
type: "POST",
data: {
"q": document.getElementById("search-articles").value,
csrfmiddlewaretoken:$("input[name=csrfmiddlewaretoken]").val()
},
headers: {
"X-CSRFToken": getCookie("csrftoken"), // be sure to utilize the 'getCookie' function
},
success: function(response) {
document.getElementById("loading").style.display = "none";
document.getElementById("search-bar").style.display = "block";
document.getElementById("articles").style.display = "block";
$("#search-bar").html(response[0]);
$("#articles").html(response[1]);
}
})
})