Reputation: 1084
I would like to use link_to
to call a controller action named show. This happens, I get a 200 message. Now I want to update a div
with the content that is being returned.
Code in controller:
respond_to do |format|
format.html # show.html.erb
format.js
end
Code in view, link and JavaScript:
<%= link_to "Show analysis", company_comparison_path(3), :remote => true , :id => "thelink" %>
<div id="replaced"> will be replaced </div>
<script>
$('#thelink').bind('ajax:complete', function() {
$('#replaced').html(data)
});
</script>
I think I still don't understand how to return the HTML or JavaScript from the controller properly into the JavaScript. If I replace the word "data" in the JavaScript with some text in brackets, I get proper output. But how do I get the result from the controller action?
Upvotes: 3
Views: 5881
Reputation: 3779
You were almost there, but you need to tell the bound function what the actual html content is you want to insert into your #results div. When you call .html()
on $('#replaced')
the variable you use (data
) is still undefined.
Try the following:
$('#thelink').bind('ajax:complete', function(event, data) {
$('#replaced').html(data.responseText);
});
edit: Oh, something to keep in mind is that this may render your view including the layout which is probably not what you want. You can add something like render layout: false if request.xhr?
to your controller to prevent the layout from showing up on ajax requests.
Upvotes: 3
Reputation: 8820
If you want to return richer content from the AJAX response, you can render the view from the controller by the :render_to_string method.
See more: http://apidock.com/rails/ActionController/Base/render_to_string
respond_to do |format|
format.html # show.html.erb
format.js {
@content = render_to_string(:partial => 'some_partial_view')
}
end
Upvotes: 1