I am creating a method of likes for a social network-type website. Currently, I can update the like count by reloading the entire page every time the user likes it. But as in the rest of the websites, it does not have this effect. I would like to eliminate the reload, but I have not been able to. I tried an asynchronous call, but it only works on the first element, and I would not know how to proceed to eliminate this update method in the likes.
HTML for each card:
<div class="col-sm-12 col-md-8 offset-md-2 mt-5 p-0 post-container">
<div class="media pt-3 pl-3 pb-1">
<a href="{% url "users:detail" post.user.username %}">
<img class="mr-3 rounded-circle" height="35" src="{{ post.profile.picture.url }}" alt="{{ post.user.get_full_name }}">
</a>
<div class="media-body">
<p style="margin-top: 5px;">{{ post.user.get_full_name }}</p>
</div>
</div>
<img style="width: 100%;" src="{{ post.photo.url }}" alt="{{ post.title }}">
<p class="mt-1 ml-2" >
<a style="color: #000; font-size: 20px;" id="like_heart" data-id="{{ post.pk }}" data-url="{% url 'posts:likes2' %}">
<i class="{% if request.user in post.likes_users.all %} fas fa-heart {% else %} far fa-heart {% endif %}"
id="success_like"></i>
</a> <i id="value_like">{{ post.likes_users.count }}</i>
</p>
<p class="ml-2 mt-0 mb-2">
<b>{{ post.title }}</b> - <small>{{ post.created }}</small>
</p>
</div>
AJAX call:
$(document).ready(function(){
// ajax for call in post
$("#like_heart").on("click",function(e){
// e.preventDefault();
var id = $(this).data("id");
$.ajax({
// url: 'posts/likes2/',
url: $(this).data("url"),
data: {
'pk': id
},
dataType: 'json',
success: function (data) {
if (data['like']) {
$('#success_like').removeClass("far fa-heart").addClass("fas fa-heart");
}
else {
$('#success_like').removeClass("fas fa-heart").addClass("far fa-heart");
}
var body = '<i id="value_like">' + data['value'] +'</i>'
$('#value_like').html( body );
}
});
})
})
View:
def likes_view(request):
pk = request.GET.get('pk', None)
post_id = Posts.objects.get(pk=pk)
likes_users = User.objects.get(username=request.user)
if post_id.likes_users.filter(username=request.user).exists():
post_id.likes_users.remove(likes_users)
else:
post_id.likes_users.add(likes_users)
data = {'like': post_id.likes_users.filter(username=request.user).exists(), 'value': post_id.likes_users.count()}
return JsonResponse(data)