Search code examples
javascriptjqueryruby-on-railsreloadlink-to

How to refresh the browser with JS after clicking a link_to tag in a Rails app


I'm trying to refresh the browser after the user clicks a link to an action that updates the database.

I want to avoid using redirect_back to prevent being sent back to the top of the screen after reload so I'm adding a JS click listener to the link_to tag with a code like this:

# in my view
<h5 class='my-link'><%= link_to 'vote', vote_path' %></h5> 

# at the bottom of my application layout
<script>
  $('.my-link').click(function (event) {
    window.location.reload(true);
  });
</script>

The JS code listener works OK in that if I click on any section of the h5 element the page will reload. However, when I click in the link the application will go to the relevant controller#action but the page wont reload.

I'm assuming I'm missing a way to execute first the link action and then force the refresh. So at click the app records a vote and then JS force a reload. Can you see any way I can achieve this? Thanks.

UPDATE

I some what solved this issue by adding a timer to the JS event so it gives time for the link to reach the controller and do the action and do the reload after it.

<script>
  $(document).ready(function() {
    $('.puke-icon, .clean-link, .comment-send').click(function() {
        setTimeout(function(){
                   window.location.reload(true); },
             50);
          });

    });
</script>

This is probably too hacky so hopefully you can provide more elegant approaches thanks!


Solution

  • In your vote controller action, use location.reload() in respond_to do format.

    respond_to do |format|
        format.js {render inline: "location.reload();" }
    end
    

    View:

    <h5 class='my-link'><%= link_to 'vote', vote_path' %></h5>

    Controller:

    class VotesController < ApplicationController
    
      def vote
        ----------------------  
    
        // your code goes here
    
        ----------------------  
    
        respond_to do |format|
        format.js {render inline: "location.reload();" }
        end
    
      end
    
    end
    

    This will reload the page after the database action is completed.