0

In a template I have a JS function to load on click a certain template of the project. I am currently using sessions to see if my facebook auth token has expired, so I need to send the user to the login template page of my project. The thing is that when I use HttpResponseRedirect in my view, the template is going to load on the certain div I want to load the content, what I need is to change the whole template in the browser.

Is there anything I can do to achieve this particular behavior?

Thanks.

aromore
  • 977
  • 2
  • 10
  • 25

2 Answers2

2

If I understand correctly, you use js to make an ajax request to a django view. That view is supposed to return an html snippet which should be rendered within a div of the calling window. However, if the auth token has expired, the view will return a 302 redirect and you want the browser to follow this redirect.

If that's your problem indeed, you can read these questions

How to manage a redirect request after a jQuery Ajax call

How to get response status code from jQuery.ajax?

which answer exactly your question (especially the first question). JQuery won't handle a redirect response the way you expect it to, it just follows the redirect and returns the new html.

You could try one of the above solutions, but let me add my 2 cents. Since you're in control of what the server will return, instead of an HttpResponseRedirect try to render a django template containing a script like this:

<script>
window.location.href = "/my-login-url"
</script>

That way jQuery (which expects an html response) will evaluate the script and redirect users to the login url.

Community
  • 1
  • 1
ppetrid
  • 3,745
  • 27
  • 29
  • Thank you! Im pretty new to web app development so probably I dont know how to express myself correctly, but you have my answer! – Cesar Flores Dec 06 '13 at 00:42
  • 1
    no problem, it's just "template" is something django will use to produce html (usually within a view) and the use of that word confused me for a moment. Glad to help anyway! – ppetrid Dec 06 '13 at 00:49
0

You will need to intercept the response and resolve redirects before they would be inserted into your div. In pseudocode:

ajaxCall('/myUrl', function (data, xhr) {
  if (xhr.status == 302) {
    window.location = xhr.headers['Location'];
  } else {
    updateDiv(data);
  }
}

For the actual implementation we would need more context. (Hint: share some code!)

Jesse the Game
  • 2,600
  • 16
  • 21