Jquery, Redirects and Django
Whenever Jquery performs an ajax call and the response has a 302 HTTP Status (redirect), the redirection is not performed.
The response is handled by Jquery as it had a HTTP 200 status code, and that’s just not right !
I had this problem with an ajax login box:
- If username and password dont check, the server sends html, that goes to the login div.
- When login is performed, server sends a redirect response that points to a private page.
The usual solution is to send a reponse with a made up status code (usually 278), check it and handle the redirection yourself.
$(document).ready(function() { $('body').ajaxComplete(function(e, xhr, settings) { if (xhr.status == 278) { window.location.href = xhr.getResponseHeader("Location").replace(/\?.*$/, "?next="+window.location.pathname); } }); });
To solve this problem with django, you can create a middleware that changes the status code from redirects performed from ajax requests:
from django.http import HttpResponseRedirect class AjaxRedirect(object): def process_response(self, request, response): if request.is_ajax(): if type(response) == HttpResponseRedirect: response.status_code = 278 return response