Reputation: 12214
Can I render a partial by binding a function to a hyperlink?
I have a hyperlink:
View All ImagesAnd I have this in application.js:
$("#allimages").click(function() {
$("#results").html("<%= escape_javascript(render 'images') %>");
});
I'm guessing that the ruby erb stuff is never executed like that. And that "render" means nothing in the context of a Javascript. But I don't want to do a complete call to the server just to display another page. Is there some way to show a partial using only Javascript? Other than displaying the page and calling visible on/off?
Upvotes: 0
Views: 1064
Reputation: 8515
I think you're mixing up application.js (pure javascript) and returning erb-processed javascript (.js.erb) files from you controller.
You'd need to do something like this instead (untested):
Set the click handler to do an ajax request:
$("#allimages").click(function() {
$.get('something/image_results');
});
In your SomethingController
:
class SomethingController < ApplicationController
respond_to :js, :only => [:image_results]
def image_results
@images = do_something
end
end
(Be sure to add a route for image_results
in routes.rb
too.)
Then in image_results.js.erb
file:
$("#results").html("<%= escape_javascript(render 'images') %>");
The key point here is that since you're now in a file that is processed by erb, you can use ruby.
The only way to do it without another call is to somehow render the partial separately and cache it either as javascript or like you said, in the page itself and then toggle it on/off.
Upvotes: 4