Brainstorm's snippets (1/247)

  Make sure request.is_ajax() return True when sending a POST request from javascript

Looks like is_ajax just checks the HTTP_X_REQUESTED_WITH (looks like X-Requested-With in HTTP) header.

If it equals XMLHttpRequest, we have an ajax query.

Example:

promise = $.ajax({
    type: 'POST',
    url: url,
    data: data,
    cache: false,
    crossDomain: true,
    dataType: 'json',
    headers: {
        'X-CSRFToken': getCookie('csrftoken'),
        'X-Requested-With': 'XMLHttpRequest'  // make sure request.is_ajax() return True on the server
    }
});

Credits: https://stackoverflow.com/questions/8587693/django-request-is-ajax-returning-false/27240729#27240729