Another Take on jQuery, Rails and respond_to

Posted by paul
on 08 May 2009

I been using jQuery to do AJAX with Rails a lot recently, and I love it. When I was starting out however, I hit the same problem that seems to trip up everyone: AJAX requests made from jQuery don't trigger format.js (or wants.js if you're cool) within the respond_to block of Rails controller actions.

The most common solution I've seen to this problem involves adding a one-liner to your Javascript to instruct jQuery to add a text/javascript Accept header to AJAX requests. Which works great in FireFox, but not in Safari.

The problem seems to be that in Safari, text/javascript is appended to the existing Accept header, so Rails sees something like text/html, */*, text/javascript which it still interprets as a request for HTML.

An alternate solution that I've been using is to add the following to environment.rb.

config.action_controller.use_accept_header = false

This instructs Rails to use the X-Requested-With rather than the Accept header to determine the request format. Since jQuery sets this header in both browsers, Rails controllers will behave as expected.

One thing to keep in mind is that if your app has an XML or JSON API, you might need to think carefully about whether this is the best way to fix this problem. For a while this became the default in Rails, although that didn't last very long.