Hi, I’m trying to make a facebook inspired ajax like button with Jquery and Django. The AJAX call is working. The button has a counter, the users’ names who have liked the post along with a CSS animation just like facebook’s (where on clicking the button, it turns blue and when clicking it again, the button goes back to normal). The problem is on reload, my CSS animation on the button is gone and I’m not able to update the counter and the user’s name on the list while on an AJAX call (Althought they work on page reload, not the CSS animation though). For CSS animation I tried to use Javascript’s localStorage method but it still won’t store the CSS animation i.e. on page reload the animation is gone. A little help would be appreciated. Here is my code:
#Like-Button-Form(i is iterating through my post model object):
<form id="like_form" method="get">
<div class="like">
<button type="button" name="post_id" id="like{{ i.id }}" data-catid="{{ i.id }}" class="like_ajax_btn" value="{{ i.id }}">
<i class="fad fa-heart"></i> Like
</button>
{% if i.like %}
<div class="show_likes">
{{ i.total_likes }} Like{{ i.total_likes|pluralize }}
<div class="username_liked">
{% for p in i.like.all %}
<div><a class="username_likes_post" href="{% url 'userprofile' p.id %}">{{ p.username }}</a></div>
{% endfor %}
</div>
</div>
{% endif %}
</div>
</form>
#Javascript/Jquery for AJAX and localstorage:
<script type="text/javascript">
$(document).ready(function(){
$('.like_ajax_btn').click(function(){
var id;
id = $(this).attr("data-catid");
$.ajax({
type: 'GET',
url: 'like/',
data: {
post_id: id
},
success: function(data) {
//$('#like' + id).toggleClass('like_ajax');
localStorage.setItem('like_ajax_btn','like_key')
console.log('button has been set')
const savedlikeclass = localStorage.getItem('like_ajax_btn')
if(savedlikeclass){
$('#like' + id).addClass('like_ajax');
}
else if($('like_ajax_btn').hasClass('like_ajax')){
$('#like' + id).removeClass('like_ajax');
console.log('removed')
}
},
error: function(){
console.log('ERRORRRR')
}
})
});
});
</script>
#Views.py:
@login_required
def like_post(request):
post_id = request.GET['post_id']
Post = post.objects.get(id=post_id)
if request.method == 'GET':
if Post.like.filter(id=request.user.id).exists():
Post.like.remove(request.user)
else:
Post.like.add(request.user)
return redirect(request.META['HTTP_REFERER'])
#urls.py:
urlpatterns = [
path('feed/', views.usersfeed, name='usersfeed'),
path('feed/like/', views.like_post, name='like_post'),
]
Please do let me know if I’m doing something wrong here.