- Check your
Gemfileforgem "jquery3", add it if it’s not there.- In
app/assets/application.js, ensure it looks like:
- In
/*
*= require_self
*//= require rails-ujs
*//= require jquery3
*/- Ensure
app/views/application.html.erbhas<%= javascript_include_tag 'application' %>
- For the form that you want to submit with AJAX, add the
data-remote="true"attribute/value to the<form>element. - Ensure that the part of the page you want to refresh with JavaScript is:
- a partial View template (like
_record_row.html.erb) - wrapped in an HTML element or some kind— usually this will be a
<div>.
- a partial View template (like
- Add an
idattribute to the containing element. If the element is related to a record in a table, usually it’s best practice to do something like
<div id="record_<%= @record.id %>">
<!-- the resulting HTML will look something like id="record_13" -->but as long as no other element on the page has that id and it makes sense to you, it should work.
In the controller action that the form submits to, add a respond_to block.
# in controller, in this example records_controller.rb
def update_record
# ...
@record.save
respond_to do |format|
format.html do
redirect_to("/modify_record/#{@record_im_updating.id}")
end
format.js do
end
end
endEach time we visit a page we need to specify the HTTP Verb (GET or POST). You can also specify the format you want to receive data as. By default, the format is HTML, but in this case, we want js for JavaScript. The respond_to block allows us to specify what happens when a person visits a route in different kinds of formats.
*If you don’t expect to use this form in an HTML context, you can remove the format.html.
- Create a
.js.erbfile, in theapp/views/record_templates/folder. In this example, I’ll call itupdate_record.js.erb. - Modify the
format.jsblock to render thejs.erbfile you created
format.js do
render("record_templates/update_record.js.erb")
end- In
update_record.js.erb, we need to identify the part of the page we want to refresh by HTMLid. This is what we chose in Step 2.
// in update_record.js.erb
$("#record_<%= @record.id %>")@record is still just an instance variable— In order for us to be able to use it here we need to make sure it’s defined in controller action that renders update_record.js.erb
- Once we select the element we want to replace, we can use the jQuery method
replaceWithto re-render the partial.
// in update_record.js.erb
$("#record_<%= @record.id %>").replaceWith("<%= j(render 'record_templates/record_row.html.erb') %>");*j is a Rails method also known as escape_javascript. We need to use it so any " inside the partial don’t conflict with the " that are in the replaceWith method.