Using JQuery with Rails

There are a number of blogs out there which talk about using JQuery with Rails.  There are many more which don’t seem to quite get the unobtrusive nature of jQuery.

I’d recently started along the path of using only jQuery with my app and I immediately ran into a problem with Internet Explorer (IE) and with Google’s Chrome browser when it came time to use the Javascript load function to load an external request into an element on my page with an xhr request.  The problem was that from the perspective of my rails controller, both IE and Chrome appeared to be making plain old html requests, not Javascript ones, so respond_to was sending them an html response.

I’d seen the fix for this issue in a number of places, but the fix only seemed to work for Firefox, not for IE or Chrome.  After poking around a bit, I found this awesome site which helped explain the problem a bit more.

If I understand correctly, the issue is more with the browsers and how they set the Default XMLHttpRequest Accept header for you.

The standard solution that I’ve seen around is to use jQuery to set the XMLHttpRequest Accept header by adding the following to your public/javascript/application.js file:

jQuery.ajaxSetup({
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})

The problem with that is that it simply appends the existing Accept headers.  As we also see from what shall be henceforth known as Grauw’s Awesome Blog, you’re unlikely to be able to unset the value by passing either ” or null to the header for Opera (apparently also the current version Chrome from my experience).  Fortunately, you can unset it for IE which is a fairly popular browser as I understand it.  So here’s my attempt at a slightly better reset of the Accept header.

jQuery.ajaxSetup({
  'beforeSend': function(xhr) {
    // First unset it, then set (which otherwise appends)
    xhr.setRequestHeader("Accept", "");
    xhr.setRequestHeader("Accept", "text/javascript");
    }
})

With this, my load’s are now working in IE and Firefox.

ps.

If I really wanted to hack this into rails for all browsers, I’m thinking I could use a unique Accept header and setup a unique respond_to, or I could add something like this to my respond_to block:

format.html { render :partial => 'my_partial' if request.xhr? }

Although, I’m not sure how well that last one will degrade.

This entry was posted in General and tagged , , . Bookmark the permalink.

One Response to Using JQuery with Rails

  1. Pingback: Random Thoughts » jQuery smart multiple DIV replace with LiveQuery

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">