Rails 3 Remote Links and Forms Part 2: Data-type (with jQuery)
Tuesday, January 18th, 2011Continued from Rails 3 Remote Links and Forms: A Definitive Guide.

Since writing the Rails 3 Remote Links & Forms Definitive Guide, one question keeps coming up:
How can we make our remote links and forms retrieve JS.ERB, instead of an HTML partial?
In the last article, we requested an HTML partial to be inserted into the page by our AJAX callbacks. But what if we want JavaScript to be executed? Or JSON or XML to be parsed? Or plain text to be displayed?
Spoiler Alert: this article concludes with a complete working example using js.erb.
Equal parts Rails & jQuery
First, we must understand the :remote => true process in Rails 3. It’s equal parts Rails and jQuery magic. But don’t worry, it’s very little magic, bundled into a 4-step process:
- Rails tells jQuery, “Hey, bind your ajaxy goodness to this sweet little link/form,” with the
:remote => trueoption. - jQuery hi-jacks the element’s click/submit event and binds it to the
.ajax()method. Now that element submits via AJAX instead of loading a new page in the browser. - Rails receives the AJAX web request when the element is clicked/submitted and responds with some content.
- jQuery receives the response content with the
.ajax()method that hi-jacked our element, and provides callbacks for us to handle the response in the page.
In this article, we’re exploring the different ways we can specify the format of the AJAX response and handle it accordingly, which actually spans all 4 steps above.


