Ror And Json: No Refresh On Button Click And Updating Count
I am trying to get follow buttons to change without refreshing the page on click. The following code works but only for the first post in the loop I am rendering in the view. The r
Solution 1:
$(document).on('ajax:success', '.follow-btn', function(e) {
// the JSON fetchedlet data = e.details[0];
// the method we are changing tolet method = this.dataset.method === 'post' ? 'delete' : 'post';
// lookup table for the textlet txt = {
post: 'Follow',
delete: 'Unfollow'
}[method];
// loop through elements with the same href
$(`.follow-btn[href="${this.getAttribute('href')}"]`).each(function() {
// change the attributes of the single node in the loopthis.dataset.method = method;
$(this).text(`${txt} (${data.count})`);
});
});
// This mocks the ajax call purely for the sake of this stacksnippets example.// Do not include this in your actual implementation
$(document).on('click', 'a[data-remote]', function(e) {
window.setTimeout(function() {
let event = jQuery.Event('ajax:success');
event.details = [{ count: 5 }, 'No Content'];
$(e.target).trigger(event);
}, 25);
e.preventDefault();
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div><p>User 1</p><ahref="/follow/1"class="follow-btn"data-method="post"data-remote="true">Follow</a><ahref="/follow/1"class="follow-btn"data-method="post"data-remote="true">Follow</a></div><div><p>User 2</p><ahref="/follow/2"class="follow-btn"data-method="post"data-remote="true">Follow</a><ahref="/follow/2"class="follow-btn"data-method="post"data-remote="true">Follow</a></div>
You can provide counts in the JSON responses by using render json:
:
def create
current_user.follow(@user)
respond_to do |format|
format.html
format.json do
render json: { count: @user.followers.count },
status: :created
endendend
def destroy
current_user.unfollow(@user)
respond_to do |format|
format.html
format.json do
render json: { count: @user.followers.count },
status: :ok
endendend
I'm just guessing the association so adjust according to your models.
Post a Comment for "Ror And Json: No Refresh On Button Click And Updating Count"