Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on rails button that switches state back and forth with ajax

I am pretty new to rails and am attempting to have two partial form_for buttons which switch back and forth on click via ajax replaceWith.

My goal is to have a follow button which when clicked switches to "unfollow", and switches the underlying button action as well. The first switch works great (and I can see in the database it went through), but when I click the newly made "unfollow" button the same idea (to switch to "follow") doesn't occur, instead it prints the text of my .js.erb file (however I can see the unfollow action gets committed to the database). Basically on the second click the correct rendering does not occur, and I'm very unsure why.

I'll post some code below, and sorry if this isn't a good question, I'm having some trouble understanding a lot of the Ajax methods.

Thank you so much! Lisa

_unfollow.html.erb

<%= form_for(@user,:remote => true,method: :delete, format: 'js') do |f| %>
<%= f.submit "Unfollow", class: "btn btn-large", id: "Submit"%>
<% end %>

_follow.html.erb

<%= form_for(@user, :remote=>true,      format: 'js') do |f| %>
<%= f.submit "Follow", class: "btn btn-large btn-primary", id: "Submit" %>
<% end %>

The create/destroy called by the controller (I would like them to switch between the two partials above)

create.js.erb

$('#Submit').replaceWith("<%= escape_javascript(raw render :partial => 'follow' )%>");

destroy.js.erb

$('#Submit').replaceWith("<%= escape_javascript(render( :partial => 'unfollow')) %>");

Again, no matter which partial/form I have on the page initially, the first click correctly switches, and the second takes the .js.erb and prints it out the page (with the html inserted)

like image 504
lmost1 Avatar asked Dec 07 '25 06:12

lmost1


1 Answers

Try replacing the entire form instead of just the submit button, like so:

_unfollow.html.erb

<%= form_for(@user,:remote => true,method: :delete, format: 'js', html: { id: "button-form" }) do |f| %>
  <%= f.submit "Unfollow", class: "btn btn-large" %>
<% end %>

_follow.html.erb

<%= form_for(@user, :remote=>true, format: 'js', html: { id: "button-form" }) do |f| %>
  <%= f.submit "Follow", class: "btn btn-large btn-primary" %>
<% end %>

create.js.erb

$('#button-form').replaceWith("<%= escape_javascript(render :partial => 'follow' )%>");

destroy.js.erb

$('#button-form').replaceWith("<%= escape_javascript(render( :partial => 'unfollow')) %>");
like image 97
Josh Rieken Avatar answered Dec 09 '25 20:12

Josh Rieken



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!