I have 2 html Pages.
A Parent Page and a Child Page. The Child Page Contains a Submit Button that runs code on the Parent Page to submit an Ajax message.
I
If you are sending a POST request body it maybe easier to add the csrf token as a request header instead. I find this approach easier to read, as it does not clutter up the request body with a token. Most AJAX request will send the csrf token as a header as suggested by the Django documentation.
function startTest(testId) {
var payload = JSON.stringify({
test_id : testId
});
$.ajax({
url: "/test-service/",
method: "POST",
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: payload,
dataType: "json"
}).done(function(response) {
console.log(response.id + " " + response.name);
}).fail(function (error) {
console.log(error);
});
}