Rails js.erb Remote Response not Executing

15 March 2011

A common issue that comes up in the GitHub Issues for the Rails jQuery UJS and the Remotipart gem / jQuery plugin goes like this:

The JavaScript response from my `js.erb` is being interpreted as text and not being executed.

I usually point to this comment in GitHub Issues, which I posted the first time I came across this problem. But GitHub Issue comments are difficult to link to, and almost useless in search results due to all their ajaxy-ness. So, I'll repost and explain here for future reference.

The problem

The problem usually isn't that the JavaScript in the js.erb isn't being executed, it's that it's being executed and incurring an error. By default, when jQuery processes a JavaScript response, it does two things. It executes (or evaluates) the response, and also returns it as a text.

Except, if there is in error in the JS evaluation, we will not see that error in our favorite JavaScript console; the automatic JS evaluation fails silently, so it appears that jQuery is only interpreting the response as text and nothing else.

Great, so now what?

The diagnosis

First, let's make sure that this is indeed what's happening. To verify that the response is getting interpreted as JS and not plain text, go to the Rails log and make sure the remote request looks like this:

JS Request in Rails Console

If the "as JS" bit is in there, then what we have is a JavaScript problem (which is addressed below). If not, then see my post on remote link and form data-type.

The solution

Here is my process for debugging this type of solution. Firebug works best, because it contains all the tools needed in one place.

  1. In Firebug, in the "Console" tab, turn on "Show XMLHttpRequests", so that we can see AJAX requests and responses in our console. Also make sure that "Larger Command Line" is enabled.
  2. Enable AJAX Requests in Console
  3. Reload the page and click the remote link or form in question.
  4. Click the AJAX request, which should have shown up in the Console, then click the "Response" tab.
  5. AJAX Request in Firebug Console
  6. Copy and paste the rendered JavaScript response into the command-line pane, and click "Run".
  7. Run rendered JS from command line
  8. Now, any JavaScript errors will show in the console. Fix the errors in the js.erb file and repeat until it works.
  9. JS error

About the author:

Steve Schwartz // Owner of Alfa Jango, CTO of Genomenon, co-founder of Carcode (acquired by Edmunds.com in 2014), engineer, developer, open-source enthusiast, guitarist, and racecar driverist.



Comments are loading...


We're Hiring!