Redirecting after AJAX post in Django
Asked Answered
J

3

33

I use Django's built-in DeleteView and I've assigned a value to the success_url attribute. Now in my template, I trigger this view via JQuery' $.post() method. When the item is deleted, I don't get redirected to the success_url. After some search, I found that it seems to be a problem of AJAX post method, which ignores the redirection.

I fixed it by adding a function to set the window.location="#myRedirectionURL" as the third parameter of $.post() in JQuery.

However, this way seems not very Django. Essentially, it solves the problem from the aspect of AJAX, instead of Django. What's more, it leaves the success_url in DeleteView useless( But you still have to assign a value to success_url, or Django will raise an error).

So is it the right way to get redirected when you post via AJAX? Is there any better way to do it?

Thanks very much.

Jarred answered 19/3, 2015 at 5:39 Comment(1)
I would execute the location.href='#myRedirectionURL' js code inside the success_url template, with a setTimeout delay while showing a nice message like 'the deletion was ok'Oblast
F
39

Ajax will not redirect pages!

What you get from a redirect is the html code from the new page inside the data object on the POST response.

If you know where to redirect the user if whatever action fails, you can simply do something like this:

On the server,

In case you have an error

response = {'status': 0, 'message': _("Your error")} 

If everything went ok

response = {'status': 1, 'message': _("Ok")} # for ok

Send the response:

return HttpResponse(json.dumps(response), content_type='application/json')

on the html page:

$.post( "{% url 'your_url' %}", 
         { csrfmiddlewaretoken: '{{ csrf_token}}' , 
           other_params: JSON.stringify(whatever)
         },  
         function(data) {
             if(data.status == 1){ // meaning that everyhting went ok
                // do something
             }
             else{
                alert(data.message)
                // do your redirect
                window.location('your_url')
             }
        });

If you don't know where to send the user, and you prefer to get that url from the server, just send that as a parameter:

response = {'status': 0, 'message': _("Your error"), 'url':'your_url'} 

then substitute that on window location:

 alert(data.message)
 // do your redirect
 window.location = data.url;
Formalism answered 19/3, 2015 at 10:17 Comment(3)
you've made it very clear for me. Thank you very much. So redirecting via AJAX codes (with a url parameter in JSON response from Django view, if necessary) is the only to solve this problem, right? Then I won't feel uncomfortable with it.Jarred
How can I pass POST data to my view . With window.location='url' I can only call a url but I cannot send custom data that should be shown in the urlInquiline
Now (Django 1.7>=) we can even use the JsonResponse to further simplify the response line, great answer though.Perversity
A
5

http://hunterford.me/how-to-handle-http-redirects-with--jquery-and-django/

Edit: source unavailable

this one works for me, perhaps looks like hack

django middleware

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

javascript

$(document).ready(function() {
    $(document).ajaxComplete(function(e, xhr, settings) {
        if (xhr.status == 278) {
            window.location.href = xhr.getResponseHeader("Location");
        }
    });
});
Atalanta answered 29/10, 2015 at 8:45 Comment(2)
The link is no longer working. Here is more information on how I get this work: 1. in settings.py, I added AjaxRedirect under MIDDLEWARE. 2. change inherited class from object to MiddlewareMixin.Overbearing
request.is_ajax() has been deprec in 3.1Ceporah
G
0

django-ajax's ajaxPost allows for redirects if you pass a normal redirect(URL) to it (as a json response). Jquery ajax() methods did not work in my case.

Gasconade answered 31/12, 2016 at 20:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.