0

I want to know how can i make my request work with ajax in my views, while i want to redirect user to other page. I mean for example, when user sends his/her email successfully and I want to redirect him/her to other page. What should I do to make this request work with ajax?

I have this function in views.py:

def compose(request, recipient=None, success_url=None, recipient_filter=None):
    if request.is_ajax():         
        if request.method == "POST":
            sender = request.user
            form = compose_form(request.POST, recipient_filter=recipient_filter)
            if form.is_valid():
               // do some processing
               if success_url is None:
                   success_url = reverse('messages_inbox')
               if request.GET.has_key('next'):
                   success_url = request.GET['next']
               return HttpResponseRedirect(success_url)
    else: //rest of function

And I check in, for example 'messages_inbox', the request to be passed with ajax. so what's the way?

j0k
  • 22,600
  • 28
  • 79
  • 90
user1597122
  • 327
  • 1
  • 6
  • 24

1 Answers1

1

The view is not the one that should redirect in case of an ajax request. Rather make the view return the success_url to the ajax call and then use the success callback to re-direct the user.

Example with jquery

$.ajax(url, data, function (data, response, xhr){
    ...
    var url = success_url; //Get success url from your data which is a json response object   
    $(location).attr('href',url);
});

You can do redirection without jquery as well, see How to redirect to another webpage in JavaScript/jQuery?

Community
  • 1
  • 1
Pratik Mandrekar
  • 9,362
  • 4
  • 45
  • 65
  • Then how will we get access to session variable or the request attribute in that page as view did not render the response. – cafebabe1991 Jul 16 '14 at 13:54
  • The existing session/request attribute would already have been available in the page http://stackoverflow.com/questions/2551933/django-accessing-session-variables-from-within-a-template. If you want the session information from the redirected request, the `response` in the callback function of ajax would have headers that you can access for session related information. – Pratik Mandrekar Jul 16 '14 at 14:05
  • But in the question you mentioned the link for ..it uses render to response.. And can you show how to retrieve info from headers – cafebabe1991 Jul 16 '14 at 14:08
  • Check `getAllResponseHeaders()` in http://api.jquery.com/jQuery.ajax/ and make sure you understand CORS if it is relevant to your situation http://stackoverflow.com/questions/2870371/why-is-jquerys-ajax-method-not-sending-my-session-cookie – Pratik Mandrekar Jul 16 '14 at 14:26