user3541631
user3541631

Reputation: 4008

Django Ajax communication, Django doesn't recognize as being Ajax (using request.is_ajax() )

I'm using Ajax with Django. The data is transmitted further but is not recognize as being Ajax. Browser Chrome/Firefox;

To check if the request is done trough ajax, I use:

`request.is_ajax()` method, but this fails, not true, so I checked this method how is working and:

def is_ajax(self):
    return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'

I verified META.get('HTTP_X_REQUESTED_WITH') and I get None;

I'm think is something with ContentType or I need to set another header. But How ?. My JavaScript is set this way :

xhr.open('post', event.target.action, true);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest");
        xhr.send(data));

At a further check seems request.Meta doesn't contain Content-type also.

Upvotes: 0

Views: 187

Answers (1)

Razem
Razem

Reputation: 1451

From the official documentation:

With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be mapped to the META key HTTP_X_BENDER.

So the name of the header should be X-Requested-With:

xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

Upvotes: 1

Related Questions