Search code examples
ajaxruby-on-rails-4submitreload

Rails 4: Submit button not responsive after its been reloaded by Ajax


I have a partial in my user show page

          <div id = "AboutMeJS">
            <%= render "about_me" %>
          </div>

The _about_me.html.erb partial is:

     <% unless @user.about.blank? %>
       <div class = "HeaderRow">
        <span class="glyphicon glyphicon-user AboutMe" aria-hidden="true"> </span>
        <div class = "Header">About <%= about_me_variable %>
        <% if current_user == @user %>
              <a class = "ProfileEdit" id = "AboutMeEdit">Edit</a>
        <% end %></div>
        <div class = "AboutMe"><%= @user.about.html_safe %></div>
      <%= render 'about_me_change' %>
     </div>
    <%end %>

This also contains a partial: _about_me_change.html.erb (not sure if this is a good idea - I am fairly new to rails):

 <div id = "AboutMeForm">
  <div class = "UserEditsJS">
    <%= simple_form_for(@user, html: { multipart: true }, remote: true) do |f| %>
    <%= f.text_area :about, class: 'form-control', :id => "edit" %>
  </div>
     <%= f.submit "Update", class: "btn btn-success AboutMeUpdateButton", id: "ThirdUpdate" %>
 <% end %>
 </div>

Finally my: about_me.js.erb

   $('#AboutMeJS').html("<%= escape_javascript(render('about_me')) %>")

The user_controller update action allows updates via ajax

   def update
     respond_to do |format|
       if @user.save
        flash.now[:success] = "Profile updated"
        format.html { redirect_to @user }
        format.js { render 'about_me'}
       else
        flash.now[:danger] = "There was a problem with your update"
        format.html { redirect_to user_path(@user) }
        format.js
       end
     end
   end
 end

This works fine ONCE. But if I then try another update - the submit button, which was reloaded after the first update is unresponsive. I have seen other questions similar to this in the setting of PHP and when the submit button is handled by jQuery (use "on" instead of "click") but not in the Rails setting.

Why is the button not submitting a second time?


Solution

  • Perhaps the reason in wrong html. about_me_change partial may look like this:

    <div id="AboutMeForm">
      <div class="UserEditsJS">
        <%= simple_form_for(@user, remote: true) do |f| %>
          <%= f.field :about, as: :text %>
          <%= f.button :submit %>
        <% end %>
      </div>
    </div>
    

    Pay your attention that simple_form_for method receives a block which will be inserted into the <form> tag. So you have to open and close <div> on the same nesting level.

    After first update, javascript replace part of the form which includes leader <form> and do not include </form>.

    P.S. multipart: true will be automatically added when it's needed.

    P.P.S. As you use simple_form gem you may use f.field instead of f.text_field method, and f.button :submit instead of f.submit. See documentation for details