Rails: Rendering a js.erb through an AJAX call

Viewed 12871

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?

7 Answers

For anyone who stumbles upon this and simply wants to call a controller action that responds with a js.erb file, I've achieved it this way (with the help of Anthony Alberto's Awesome Answer).

Controller Action

def some_action
  ..
  respond_to do |format|
    format.js { render 'some_action' }
  end
end

some_action.js.erb

...
$('#someActionWrap').html('<%= j render "some/displaypartials/action_partial" %>')
...

Ajax call

var id = '<%= @someresource.id %>';
$.get('/someresource/' + id + '/action/', null, function(data){
    eval(data)
}, 'script');

i have a similar problem on link_to helper but this were corrected using remote:true

Related