javascript - ajax like count is showing the same for every post in django -
the problem due ajax implementation in django twitter clone app, count every post showing same after clicking button.but after page refresh okay. near solve problem stuck somehow.
view:
def add_like(request): if request.method == 'get': ans_id = request.get['id'] user = request.user.profile liked_tweet = get_object_or_404(tweet, pk=ans_id) if ans_id: # creating instance sending table fields instance, created = like.objects.get_or_create(liker=user, liked_tweet=liked_tweet) ans = tweet.objects.get(id=(int(ans_id))) if ans: likes = ans.likes + 1 ans.likes = likes ans.save() # returns likes field of tweet post return httpresponse(likes)
the httpresponse sending likes , creates problem guess.
the template:
{% tw in tweets %} <div class="blog-post"> <p> {{ tw.content|safe }}<br><hr> <small class="small"> লিখসে - <!-- in "href" can pass data "pk", accessing structure current object based on--> <a href="{% url 'profile' pk=tw.tweeter.user.pk %}">{{ tw.tweeter.user.username|capfirst }}</a> </small> </p> {% if user.is_authenticated %} <button class="btn btn-default likes-button" type="button" data-ansid="{{ tw.pk }}">like</button> <i> total likes: </i><em class="like_count">{{ tw.likes }}</em> {% endif %} </div>
the ajax script:
$(".likes-button").click(function(e) { if ($(this).html() == "like") { $(this).html('unlike'); //alert("js working"); // error there "data" insted of "attr" var ansid = $(this).attr("data-ansid"); $.ajax({ url: '{% url "add_like" %}', type: 'get', data: {id: ansid} }).done(function (data) { alert("success"); $('.like_count').html(data); //$('#likes').hide(); }).fail(function (err) { alert(err); }); }
thanks in advance.
i think first comment sayse gives answer. trying give bit more explanation.
so have done after successful ajax request, replace existing count data ajax in element have class named .like_count
.
check in code $('.like_count').html(data);
select elemnt having like_count
class , change html.
instead, should've done after successful ajax, change data in 1 place. you need choose appropriate jquery selector.
something .closest()
can used. in case, use (following code not tested) $(this).closest('.like_count').html(data);
apeend 'like count' in appropriate element.
also can assign dynamic id each 'like count' element based on id , use exect id selector.
hope helps.
cheers!
Comments
Post a Comment