About Ajax Calls using Fetch API
If you are using fetch API and want to recognize an Ajax call, you have at least two options:
1. Pass X-Requested-With: XMLHttpRequest header from the fetch call (jQuery and some other JavaScript libraries do that by default):
let form = document.getElementById('comment_form');
fetch(form.getAttribute('action'), {
method: 'POST',
body: new FormData(form),
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
});
Determine if that was an Ajax call in the view with:
is_ajax = request.headers.get("X-Requested-With") == "XMLHttpRequest"
posted_data = request.POST
2. Pass the form data as JSON:
let form = document.getElementById('comment_form');
let formData = new FormData(form);
let data = Object.fromEntries(formData.entries());
const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
fetch(form.getAttribute('action'), {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken,
},
});
Then read the data in the view as:
is_ajax = request.content_type == "application/json"
posted_data = json.loads(request.body)
Tips and Tricks Programming Django 6.x Django 5.2 Django 4.2 JavaScript
Also by me
Django Messaging
For Django-based social platforms.
Django Paddle Subscriptions
For Django-based SaaS projects.
Django GDPR Cookie Consent
For Django websites that use cookies.