How to Use AJAX with Django: GET & POST Requests Made Easy
This tutorial explains how to integrate AJAX fetch calls with Django views for both GET and POST requests, covering header configuration, CSRF handling, JSON data exchange, and the updated method for detecting AJAX requests in Django 3.1 and later.
When serving web pages with Django, any user action that changes the page causes the full HTML template to be sent to the browser. To update only a part of the page without a full reload, you can use AJAX.
GET Request
Use the fetch API to send a GET request to a Django view and receive JSON data without refreshing the page. Set appropriate headers, including 'Accept': 'application/json' and 'X-Requested-With': 'XMLHttpRequest', so the view can recognize the request as AJAX.
fetch(URL, {
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest' // Required for request.is_ajax()
}
})
.then(response => response.json())
.then(data => {
// Use the response data here
});The URL is passed as the first argument and may contain path parameters or query strings defined in Django's URLconf.
Handling GET in a Django View
A simple function‑based view can return a JsonResponse with the data you want to send back.
# views.py
from django.http import JsonResponse
def ajax_get_view(request):
data = {
'my_data': data_to_display
}
return JsonResponse(data)The view can also accept additional URL parameters to query the database and include the results in the JSON response.
POST Request
POST requests require extra parameters such as method: 'POST', credentials, and the CSRF token.
fetch(URL, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRFToken': csrftoken
},
body: JSON.stringify({
'post_data': 'Data to post'
})
})
.then(response => response.json())
.then(data => {
// Use the response data here
});To obtain the CSRF token from the cookie, use the following JavaScript helper:
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
const csrftoken = getCookie('csrftoken');Handling POST in a Django View
The view reads the JSON payload, processes it, and returns a JsonResponse.
# views.py
from django.http import JsonResponse
import json
def ajax_post_view(request):
data_from_post = json.load(request)['post_data'] # Get data from POST request
# Process the data as needed
data = {
'my_data': data_to_display,
}
return JsonResponse(data)After extracting the data, you can create or update model instances and send back a success message or the updated object.
Ensuring the Request Is AJAX
Use the request.is_ajax() method (deprecated in Django 3.1) or check the header manually:
# views.py
from django.http import JsonResponse
def ajax_view(request):
if request.is_ajax():
data = {'my_data': data_to_display}
return JsonResponse(data)In Django 3.1+, replace the check with:
if request.headers.get('x-requested-with') == 'XMLHttpRequest':
# Process AJAX request
return JsonResponse(data)Important Notes
The fetch API is not supported by older browsers such as Internet Explorer; consider using jQuery or XMLHttpRequest for compatibility.
Use AJAX only for small, isolated parts of a Django project. For larger data interactions, consider building a REST API with Django Rest Framework.
Summary
By incorporating AJAX fetch calls into a Django project, you can update specific page sections without a full reload. The fetch API makes this straightforward with minimal JavaScript, and proper use of headers, CSRF tokens, and JSON handling ensures a smooth, interactive user experience.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
