XHR Redirects

All my ‘Ajax’ requests, use simple xhr when they want to load html, and not .js ,which imo is a misuse since requesting .js should yield a json response.

The first thing i always do is define a xhr layout, which usually is nil. Who ever thought that any xhr request should ever respond with stylesheets and javascript?

layout proc {|controller| controller.request.xhr? ? nil :  'application' }

Working this way i came to some limitations of the xhr approach:

  • cannot easily request from the browser
  • cannot redirect

Redirect an xhr ?

When a user requests something in a Lightbox, it is render using xhr. When the requested resource is not accessible by this user, he should see a login screen. This can be done with a normal redirect, which the JS Framework(at least jQuery does) uses to render the login page inside the lightbox.

Sounds good? But does not work…

Redirects will have the default layout, since they are no longer xhr request, which messes up the lightbox.

Xhr redirects

With this xhr redirect plugin the problem should go away.


The plugin uses an added parameter _xhr to signal if a request is xhr or not, so now one can also request a page with _xhr=1 and see the actual xhr response.

One thought on “XHR Redirects

  1. Awesomes. We were using the exact same trick to support full-on graceful js degradation in a very Ajax-heavy app and ran into the same issue with redirect. I’ve been banging my head against the best way to handle it for a few hours now (sigh, must be tired).

    This approach is a little hacky but works perfectly in practice. Good stuff, and thanks for sharing!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s