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?
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With