Is there a way to check if a request is AJAX in Python?
The equivalent of PHP's $_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest'
?
Is there a way to check if a request is AJAX in Python?
The equivalent of PHP's $_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest'
?
If the AJAX framework sets the X-Requested-With header in its requests, then you will be able to use that header to detect AJAX calls. It's up to the client-side framework to do this.
Getting hold of the HTTP headers depends on your Python framework of choice. In Django, the request
object has an is_ajax
method you can use directly.
is_ajax()
method is deprecated as of Django version 3.1. –
Franco is_ajax()
is deprecated in django 3.2 and forward as of 28th May, 2021. –
Vidal HttpRequest.is_ajax()
is in fact deprecated since Django 3.1. Have a look to the changelog here. The changelog gives us the solution : check if request.headers.get('x-requested-with') == 'XMLHttpRequest'
–
Byrd is_ajax()
is deprecated since Django 3.1 (as of 28th May, 2021) as they stated that it depends on jQuery ways of sending request but since people use fetch
method a lot to make call Ajax calls, it has become unreliable in many cases.
Usually, text/html
is requested in the header in the first option in the browser when it just the loads the page. However, if you were making API call, then it would become */*
by default, if you attach Accept: application/json
in the headers, then it become
application/json
So, you can check easily if the request is coming from ajax by this
import re # make sure to import this module at the top
in your function
requested_html = re.search(r'^text/html', request.META.get('HTTP_ACCEPT'))
if not requested_html:
# ajax request it is
Check this how to check if request is ajax in turbogears
also this for how to do this in Django(it depends in your framework): How to check contents of incoming HTTP header request
Just in case someone can find this useful, the Sec-Fetch-Dest can hint if the request is an ajax call or not.
So one could have something like this:
is_ajax_call = all(
request.headers.get("Sec-Fetch-Dest", "")
not in secFetchDest for secFetchDest in ["document", "iframe"]
)
Generally speaking, check if the request header attribute x-requested-with
is equal to XMLHttpRequest
.
From Django 4.0 :
def is_ajax(request):
return request.headers.get('x-requested-with') == 'XMLHttpRequest'
def view(request):
if is_ajax(request):
...
Source : Django 3.1 changelog
© 2022 - 2025 — McMap. All rights reserved.
request.is_ajax()
– Croquet