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);
});
}
Going through the jQuery source, it looks like
$.ajax()
(and therefore$.get()
,$.post()
, etc) will automatically set thecrossDomain
option totrue
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 theHTTP_X_REQUESTED_WITH
header that Django needs foris_ajax()
ifcrossDomain
is set (relevant code here).I think the easiest way to fix this is to explicitly set
crossDomain
tofalse
: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.You may also want to take a look at this page. Because Django provides some protection against cross-site request forgeries (CSRF), it requires some special AJAX setup. I've included the AJAX setup below: