jQuery on Rails

Though I feel a little late to the party, I’ve recently discovered the joy of jQuery.  I did have some trouble though getting it to work with the Rails app I’ve been working.  Here’s what I came across in case it helps anyone else.

Most examples you see on the web for using rails use the following in the controller for handling and responding to an ajax request:

respond_to do |format| format.js {} format.html { render :text => "Location Changed!" } end

The problem was I kept getting a syntax error in the JavaScript returned to the page. After several hours of trying different things, I realized it was rendering the JavaScript specified in the .js.erb file wrapped inside the layout html. In order to fix this I did the following:

respond_to do |format| format.js { render :layout => false } format.html { render :text => "Location Changed!" } end

I suppose the other thing that could be done is to not render the layout for the action handling the ajax request.

layout "main", :except => :yourajaxaction