nullnullnull nullnullnull - 6 months ago 11
Ajax Question

Rails: Rendering a js.erb through an AJAX call

From JavaScript, I'm calling a controller via AJAX like so:

$.ajax({
type: 'GET',
url: '/books'
}


In my controller I have:

def index
render 'lightbox.js.erb'
end


In my routes I have:

resources :books do
member do
get :lightbox
end
end


In lighbox.js.erb I have:

alert("Hello world!");


For some reason, the alert is never getting called. I don't get any error messages, either through the server or through Firebug. I'm at a loss for what could be going wrong. Any ideas?

Answer

It turns out that on the client-side, my JavaScript was being rendered as text. I confirmed this by looking at the console feed. It said:

Started GET "/books/lightbox?book=4&username=tbaron&_=1344009191129" for 127.0.0.1 at 2012-08-03 10:53:11 -0500
Processing by BooksController#lightbox as text

Those last two words should have read "as JS." After rooting around, I found this blog post which led to a surprisingly simple solution. Add "dataType: script" to the AJAX call:

$.ajax({
  type: 'GET',
  url: '/books'
  dataType : 'script'
}

Thanks for your help, everyone!