Redirect being performed on server when via AJAX call?

Hi,

I’m having a hard time understanding why when I make a request via an
AJAX call that triggers a redirect, the redirect seems to be performed
by the server and the response of that subsequent request is the one
sent back to the client.

I am aware I can send back JavaScript in the response to perform the
location change rather than a redirect but I’d like to have the 302
response sent to the client, if possible. Prototype.js has the ability
to bind an event to a 302 status, yet the client only ever gets the 200
OK response of the request made to the redirect page.

Anyone care to enlighten me?

Many thanks
Ian

Ian wrote:

Hi,

I’m having a hard time understanding why when I make a request via an
AJAX call that triggers a redirect, the redirect seems to be performed
by the server and the response of that subsequent request is the one
sent back to the client.

I am aware I can send back JavaScript in the response to perform the
location change rather than a redirect but I’d like to have the 302
response sent to the client, if possible. Prototype.js has the ability
to bind an event to a 302 status, yet the client only ever gets the 200
OK response of the request made to the redirect page.

Anyone care to enlighten me?

Many thanks
Ian

OK, I’ve finaly managed to track down what’s going on here (after way
too long). XMLHttpRequest will transparently follow redirect responses
(may be different from browser to browser though). So if you’re doing an
AJAX call to replace a div (or whatever) with the returned content and
you trigger a redirect you’re going to get the content of the redirect
page in your div. If you send back some javascript (which Prototype will
evaluate) to set location.href you’ll get redirected, but you’ll also
see the text in your div before it does (due to using the :update
callback on your form). So the way round this is to render whatever you
need on the backend and send it to the frontend as Json along with some
status inforation and do your div upadting or redirection there.

Hope this saves someone the time I wasted trying to figure it out :slight_smile:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs