Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 789
nullnullnull Avatar asked Aug 02 '12 23:08

nullnullnull


2 Answers

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!

like image 73
nullnullnull Avatar answered Nov 03 '22 09:11

nullnullnull


I think that's because you need to call books.js :

$.ajax({
  type: 'GET',
  url: '/books.js',
  success: function(data) {
    eval(data);
  }
}

In index action :

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

And lightbox.js.erb should be in app/views/books

If it still doesn't work, try calling books/index.js You can also use firebug/chrome to check what the server is responding to your ajax call

like image 34
Anthony Alberto Avatar answered Nov 03 '22 09:11

Anthony Alberto