I am trying to build a ajax powered like button, but the ajax code is not working.
views.py
def like_button(request,postid):
postresult=get_object_or_404(post,id=postid)
if postresult.user_like.filter(id=request.user.id).exists():
postresult.user_like.remove(request.user)
else:
postresult.user_like.add(request.user)
noresdat=postresult.totallikes
response_data_to_dump={'success': True,'likes':noresdat}
data = json.dumps(response_data_to_dump)
return HttpResponse(data, content_type='application/json')
while template is as follows:-
{% for p in result %}
<div class="SpriteContainer">
<a class="postlike" href="/like/{{ p.id }}"><img src="{%static "/images/icons/heart.png" %}"/></a>
<p class="nolike" style="display: inline-block;">{{ p.totallikes }}</p></div>
{% endfor %}
<script>
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
$(".postlike").click(function(e){
e.preventDefault();
var $this = $(this);
var url = $(this).data("action");
$.post(url, function(response){
if(response && response.success==true)
$this.next(".nolike").text(response.likes);
});
});