Reputation: 2728
I am sending a remote form via submit.rails when a user clicks a checkbox in my app which works great. Now there is a value inside a div that would need to get refreshed immediately after the form was sent. After researching a bit how to realise this, I came to this solution inside my jquery function:
$( "input#my-checkbox" ).click(function() {
$(this.form).trigger('submit.rails');
$("#count-items").load();
});
this doesn't work because the load() function requires something to load e.g. a specific view. I cannot load a view into my div so I created a partial but that would not render correctly. There must be a much more simple way to refresh what is inside my div.
<div id="count-items"><%= render "pages/count_items" %></div>
The above also does not work as explained. The partial would not render here on load().
How could I simply reload the div content (foo) which would look like this:
<div id="count-items"><%= foo %></div>
after I hit my checkbox (click event) from the above code?
Upvotes: 1
Views: 916
Reputation: 56
Here is how I handle this kind of interaction. It is probably not the only solution, but it has been working well for me. In your view, when you want something to be rendered as a result of an ajax request, you also need to create a request to the server, the server returns a response, and you render that response in the desired html node.
In the view (something like this, I've updated it from coffeescript), let's say you are updating the checkbox counter (url -> /checkboxes/update_counter)
$("input#my-checkbox").click(function() {
$.ajax(
type: "POST",
data: {key: 'value'}, //$(this.form).trigger('submit.rails'); should be handled here
url: "/checkboxes/update_counter",
dataType: "script",
success: function(data){
$("#count-items").update(data);
}
)
}
I don't really think the $("#count-items").trigger('submit.rails') is necessary, you can use the post to transmit your data.
In the corresponding controller, if necessary, you should define a format.js in the respond_to block, if no respond_to is defined, rails should automatically try to retrieve a update_counter.js.erb
So in your controller (do not forget to create the corresponding route if necessary):
...
def update_counter
@new_count = do_update_counter
end
...
in your update_counter.js.erb view:
$("#count-items").html("<%= escape_javascript(render "pages/count_items", locals: {new_count: @new_count}) %>");
I hope this help. Let me know if you need more explanation.
Regards
Upvotes: 1