How can I update a count on my view without refreshing the page when a button is clicked?
application.js
$(document).on('ajax:success', '.follow-btn-show', function(e){
let data = e.detail[0];
let $el = $(this);
let method = this.dataset.method;
if (method === 'post') {
$el.text('Unfollow');
this.dataset.method = 'delete';
} else if (method === 'delete') {
$el.text('Follow');
this.dataset.method = 'post';
}
});
The code above changes the button text perfectly. But now how do I update a count in a different div upon click? I attempted:
$(this).text(
${data.count});
However, it updates in the wrong place. How can I assign the correct attribute to my script for the update?
Here's the count in my view
<div class="loop"><b><%= @user.followers.count %></b></div> Followers
Controller
def create
current_user.follow(@user)
respond_to do |format|
format.html
format.json do
render json: { count: @user.followers.count },
status: :created
end
end
end
def destroy
current_user.unfollow(@user)
respond_to do |format|
format.html
format.json do
render json: { count: @user.followers.count },
status: :ok
end
end
end
Any suggestions or guidance would be appreciated!
Thanks