Context: a chrome browser extension uses JQuery to request a response from a remote django app. Django recognizes that the request is made via AJAX and responds with "Hello AJAX!". I'm basing my exercise off this great example. Because this request is being made from a chrome extension, the request is being made cross site, so I've used the @CSRF_exempt
decorator on my Django view.
Problem: My Django view is not recognizing the request as an AJAX request, and instead of responding Hello AJAX!
it responds Hello not AJAX!
.
My Django view:
(The url /xhr_test
uses the following view)
@csrf_exempt
def check_login_extension(request):
if request.is_ajax():
message = "Hello AJAX!"
else:
message = "Hello not AJAX"
return HttpResponse(message)
My JQuery request:
function xhrconnect() {
$.get("http://localhost:8000/xhr_test", function(data) {
document.getElementById('xhrmsg').innerHTML = (data);
});
}
Django's request object has a nifty little method is_ajax . It allows determining whether a request comes from a JS framework (aka old-school ajax). While it works fine with some JS libraries, including the venerable jQuery , it won't work with modern JS native fetch API out of the box.
Using Ajax in Django can be done by directly using an Ajax library like JQuery or others. Let's say you want to use JQuery, then you need to download and serve the library on your server through Apache or others. Then use it in your template, just like you might do while developing any Ajax-based application.
processData. If set to false it stops jQuery processing any of the data. In other words if processData is false jQuery simply sends whatever you specify as data in an Ajax request without any attempt to modify it by encoding as a query string.
Going through the jQuery source, it looks like $.ajax()
(and therefore $.get()
, $.post()
, etc) will automatically set the crossDomain
option to true
if it sees that you're making a cross-domain request, which you are (relevant code here). And in the actual AJAX request, jQuery won't set the HTTP_X_REQUESTED_WITH
header that Django needs for is_ajax()
if crossDomain
is set (relevant code here).
I think the easiest way to fix this is to explicitly set crossDomain
to false
:
function xhrconnect() {
$.ajax({
url: "http://localhost:8000/xhr_test",
success: function(data) {
document.getElementById('xhrmsg').innerHTML = (data);
},
crossDomain: false
});
}
If that doesn't work, you could try using an AJAX prefilter function to manually set the HTTP_X_REQUESTED_WITH
header on the request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With