Kellogs
Kellogs

Reputation: 471

Rails: Partial Refreshing on button click

I just recently made a voting system that has a vote tallier for each time a user clicks on the vote button for a post and at the same time a counter that tracks the amount of votes the user made. The vote button refresh only that part of the HTML so without the whole page refreshing the vote tally number changes but the counter of vote amounts doesn't change unless the whole page is refreshed. How can I make it so that both with refresh only their part when the vote button is clicked upon? Just not sure where to start. Thank you!

HTML for Vote

<div class='Counter'>
<span class='CounterNum'><span id='<%= micropost.id%>'><%=micropost.votes_for %></span></span>
<div class='<%=micropost.id %>'>
<a href="/microposts/<%=micropost.id %>/vote_up" data-remote='true' class='CounterButton b2'>
<span id="CounterIcon" class="<%=micropost.id%>"></span>
</a>
</div>
</div>

HTML for Vote Amount

<li class='fst'><a class='ProfileLikes' href="/"><%[email protected]_count(:up) %><span class='ProfileStatText'>Likes</span></a></li>

Vote_up.Js

$("#<%[email protected]%>").html('<%="#{@micropost.votes_for}"%>');
$(".<%[email protected]%>").html('<a href="/microposts/<%[email protected]%>/unvote" data-remote="true" class="SquekCounterButton b3 <%[email protected]%>"><span id="SquekCounterIcon" class="<%[email protected]%>"></span></a>');

Upvotes: 0

Views: 983

Answers (1)

Nick Bork
Nick Bork

Reputation: 4841

The jQuery API Guide for an AJAX request can be seen here: http://api.jquery.com/jQuery.ajax/

There is a lot of information there so I'll give you some code to get you started:

 $(document).ready(function(){
      $('a.CounterButton').click(function(event){
           event.preventDefault(); //This will prevent the link from navigating

           $.ajax({
                url: $(this).attr('href'), //This pulls the URL from the HREF of the link
                dataType: 'json', //This tells the AJAX request we're expecting JSON 
                success: function(response){
                     console.log(response); //Output the response to console
                     //Maybe something like:
                     $('#' + response.ID ).text(response.Likes);
                },
                error: function(jqXHR, textStatus, errorThrown){
                     alert('An error occured!');
                }
           )};
      });
 });

Upvotes: 1

Related Questions