Created
August 20, 2014 03:52
-
-
Save adagio/775818fb787f2cddc4e0 to your computer and use it in GitHub Desktop.
Executing action with Ajax in RoR, and modifying html without refreshing the page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
<tr id="<%= day.id %>"> | |
... | |
<td><%= link_to 'Total', total_day_path(day), :remote => true %></td> | |
... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$("tr#<%= @day.id %> td.oTotal").html("<%= @day.oTotal %>"); | |
$("tr#<%= @day.id %> td.dTotal").html("<%= @day.dTotal %>"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
def myaction | |
... | |
respond_to do |format| | |
format.js {} | |
end | |
end | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In index.html.erb we produce a link that triggers an ajax action when clicked by means of :remote => true. In this example the entity or model is Day and the action is total.
Notice that we render day.id as id for the html element we want to manipulate. This is how we could identify and work with that specific element (any element in the identified row).
Let's look at myentity_controller.erb. There we got the repond_to block and the condition format.js {}. This indicates that javascript will be sent as response and the correspondent code must be included in a js.erb view with the name of the action (e.g. myaction.js.erb).
In myaction.js.erb we can use JQuery to manipulate the dom and html elements with the powerful help of Rails bindings.