1

The problem is due to the ajax implementation in my django twitter clone app, the like count for every post is showing the same after clicking the like button.but after the page refresh that is okay. I am near to solve the problem but 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 by sending the Like 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 the likes field of a tweet post
return HttpResponse(likes)

the HttpResponse is sending the likes and that creates the problem I guess.

the template:

    {% for tw in tweets %}
    <div class="blog-post">
        <p>
            {{ tw.content|safe }}<br><hr>
            <small class="small">
                লিখসে -
                <!-- in the "href" we can pass data like "pk", accessing by the structure the current object is 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 was there for "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.

before hitting like after hitting like

Shohanul Alam
  • 145
  • 1
  • 12
  • I believe the problem is because you're setting the html of a very broad `$('.like_count')` element, you need to give it a more strict element to apply it to, (not got time atm to make a full answer) – Sayse Jul 11 '16 at 10:50
  • Thanks @Sayse but I didn't get that very well. May be I'll wait some time to get a proper solution when you get time. Thanks for the reply and I am checking this out. – Shohanul Alam Jul 11 '16 at 10:59

2 Answers2

1

Did you say:

but after the page refresh that is okay

Since your code snippet works, you're simply looking for the likes count incrementation to happen and see the live update in the template.

Well, in theory, here:

  • The function that increments the like should return with a JSON response of the incremented value from the database.
  • A client function standing by accepts this JSON response, and updates the template value accordingly.

In Practicals:

Community
  • 1
  • 1
KhoPhi
  • 9,660
  • 17
  • 77
  • 128
1

I think the very first comment by Sayse gives your answer. I am just trying to give a bit more explanation.

So What you have done is after a successful ajax request, you replace existing like count with the data you get from ajax in any the element who have a class named .like_count.

Check In your code $('.like_count').html(data); This select all the elemnt having like_count class and change the html.

Instead, what you should've done is after a successful ajax, change the data only in one place. You need to choose appropriate jquery selector.

Something like .closest() can be used. In that case, use (following code is not tested) $(this).closest('.like_count').html(data); to apeend 'like count' in appropriate element.

Also you can assign dynamic ID to each 'like count' element based on id and then use exect ID Selector.

Hope this helps.

Cheers!

arifin4web
  • 696
  • 8
  • 12
  • Thanks a lot. Really. Your descriptive explanation cleared my problem. I just used this in the template: and in ajax: $('#'+ansid).html(data); You saved me from hell man, Cheers and stay cool :) – Shohanul Alam Jul 13 '16 at 15:52