rubyajaxruby-on-rails-4button-to

Ruby on rails: Button_to Check post result and update current page


In my UI, I have a table of items. Each row has a favorite button. I am using button to make a rails call to add the db association.

I've been looking into how to check the result of the post response in my button to call.

If it succeeds, I want to disable the favorite button on my page and if it doesn't I want to nothing. Is there a way to check the post response in my button to call and is there a way to stay on the page?

Heres a sample of what I have

<%= button_to create_favorite_path(res.id), class: "favorite-btn-#{res.id} btn btn-default" do%>
  <i class="glyphicon glyphicon-star-empty"></i>
<% end %>

Solution

  • To stay on the page when you click the button, you need to add remote: true to your button call. This will make your button request an AJAX call by default.

    Read more about the button_to helper here.

    <%= button_to create_favorite_path(res.id), remote: true, class: "favorite-btn-#{res.id} btn btn-default" do%>
      <i class="glyphicon glyphicon-star-empty"></i>
    <% end %>
    

    Then to see the response of this AJAX request, you'll need to write some javascript.

    In your application.js or whatever javascript file you have on this page:

    $(document).on('ajax:success', 'form', function(event, data, status, xhr) {
      // do something with data or status
    });
    

    Read more about working with javascript in Rails here.