X-CSRFToken Header Resets Session Object

June 14, 2015

I am using the jQuery code from Django documentation in order to send post requests via ajax. When a link is clicked from a page, it opens another page in a new tab, and at the same time sending an ajax request.

The ajax request, for some reason, is resetting the Session object. The effect is, any new data added in the session (in the non-ajax request) will be lost.

Solution (or rather "workaround"):
After some investigation, the problem lies somewhere in the csrf middleware. I'm still unable to find where the problem is within the middleware, but to patch the issue, I modifed the javascript code to send null X-CSRFToken for non-POST requests. The new code now looks like this:

    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
            xhr.setRequestHeader("X-CSRFToken", null);