FP89
FP89

Reputation: 43

How to use Ajax "like" button on Django posts list

I created my first site with Django and I'm trying to make the Ajax "like" button work on the listing posts page, but I have to reload the page to have +1.

My views:

def likes_post(request):
    post_id = None

    if request.method == 'GET':
        post_id = request.GET['post_id']

    like = 0

    if post_id:
        post = Post.objects.get(id = int(post_id))
        if post:
            like = post.likes + 1
            post.likes = like
            post.save()
        return HttpResponse(like)

My HTML template:

{% for post in posts %}
 <div class="post-favourite">

<a href="#" data-posts-id="{{post.id}}" class="like text-danger">J'aime <i class="fa fa-heart-o likes_count"aria-hidden="true"> {{ post.likes }}</i></a>

</div>

{% endfor %}

and the Ajax function:

<script type="text/javascript">
$('.like').click(function(){
    var ps_id;
    ps_id = $(this).attr("data-posts-id");
    $.get('/likes_post/', {post_id: ps_id}, function(data){
        $(this).prev().find('.like_count').html(data);
    });
});
</script>

The Ajax button for the post detail page works by simply replacing the last line with

$('.like_count').html(data); 

Upvotes: 1

Views: 221

Answers (1)

Amir big
Amir big

Reputation: 102

in your views.py, you should send back data to jquery with JsonResponse

from django.http import JsonResponse

def likes_post(request):
   post_id = None
   if request.method == 'GET':
        post_id = request.GET['post_id']

    like = 0

    if post_id:
        post = Post.objects.get(id = int(post_id))
        if post:
            like = post.likes + 1
            post.likes = like
            post.save()
        return JsonResponse({'like':like})


and then in your jquery:

<script type="text/javascript">
$('.like').click(function(){
    var ps_id;
    ps_id = $(this).attr("data-posts-id");

$.ajax({
        url: '/likes_post/',
        method: 'GET',
        data: {
            'post_id': ps_id,
        },
        success: function(data){
            $(this).prev().find('.like_count').html(data);
            $(this).html(data);
        }

    });
});
</script>



whatever you send with JsonResponse is accessible in success part of jquery. in this example the like we send is data in success part.

in success part you can write data in your html code

Upvotes: 2

Related Questions