I'm trying to use AJAX to replace the inner HTML of a div element when I press a button. The div should change to a simple form like this, which will create a "contribution" resource when filled out:
<%# ???.html.erb %>
<h2>Make a contribution:</h2>
<%= form_with(model: [ @event, @event.contributions.build ], local: true) do |form| %>
<p>
<%= form.label :text %><br>
<%= form.text_field :text %>
</p>
<p>
<%= form.submit %>
</p>
<% end %>
I'm still new to Rails, but I've managed to use this tutorial to get partway there. So far, I've written something like this:
// contribution_script.js
$(document).on('turbolinks:load', function() {
$('[data-js-new-contribution]').click(function(event){
event.preventDefault();
divElement = ... // get the div element
$('#' + divElement.id).html("<%= j (render partial: '???') %>");
});
});
This does successfully replace the content of the div, but since this is in a .js file rather than a js.erb file, it doesn't process the Ruby code and simply changes the div to the raw string.
Here's what the tutorial says about using .js.erb files:
Put this code in a file with an extension of .js.erb, with the name of the current action (like create.js.erb) & inside the views folder.
On the controller you can render this view just like any other view.
This is confusing to me: I get that my .js.erb file has to go somewhere in my views folder, but what is my "current action?" The page where this div will be displayed comes from views/events/index.html.erb, so I guessed that my current action is "index" in events. Based on this Stack Overflow question, I wrote the following in my events controller:
def index
@events = Event.all
respond_to do |format|
format.html
format.js
end
end
Then I took the JavaScript code above, renamed it "index.js.erb," and put it in my views/events folder. This doesn't seem to do anything. So, how do I make this work? Thanks for your time!
Bonus question: once I do get the js.erb file working, how can I actually render the form from an html.erb file? I looked at this question, but I'm still unsure how to set up the partial so it will have the necessary information about the event which the contribution will be added to.