user1597122
user1597122

Reputation: 327

Make redirect url work with ajax

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?

Upvotes: 0

Views: 1649

Answers (1)

Pratik Mandrekar
Pratik Mandrekar

Reputation: 9568

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?

Upvotes: 1

Related Questions