JohnWire
JohnWire

Reputation: 97

Ajax + Django Like button

I have problems while I am building a simple like button. I have done everything as I have read in different tutorial but when I click on the Like button, it does not do anything. Look:

models.py

class Comentario (models.Model):
    titulo = models.CharField(max_length=50)
    texto = models.CharField(max_length=200)
    autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE)
    likes = models.IntegerField(default=0)

views.py

def like (request):

    com_id = None

    if request.method == 'GET':
        com_id = request.GET.get('comentario_id')

    likes = 0
    if com_id:
        com = Comentario.objects.get(id=int(com_id))
        if com:
            likes = com.likes + 1
            com.likes =  likes
            com.save()
    return HttpResponse(likes)

urls.py

urlpatterns = [
    url(r'^like/$', login_required(views.like), name='like'),
]

.html

{% extends 'base/base.html' %}
{% for comentario in objects %}
...
{% if user.is_authenticated %}
            <button id="likes" data-comid="{{comentario.id}}" class="btn btn-warning btn-sm " type="button">
            Like|<strong id="like_count">{{ comentario.likes }}</strong> 
            </button>

{% endif %}
{% endfor %}    

js/ajax.js

$('#likes').click(function(){
    var comid;
    comid = $(this).attr("data-comid");
$.get('/home/like/', {comentario_id: comid}, function(data){
          $('#like_count').html(data);
       $('#likes').hide();
    });
});

And in base.html I have import all the .js

base.html

        <script src="{% static 'jq/jquery-3.2.1.min.js' %}"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
        <script src= "{% static 'js/bootstrap.min.js' %}"></script>
        <script src= "{% static 'js/ajax.js' %}"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

The issue is that when I push the button nothing happens. It is a simple code but somethin crashes. In the inspection do not show any error or something missing.

When I enter into .../home/like/ it appears a 0.

I will appreciate your help. Thank you so much.

Upvotes: 0

Views: 1154

Answers (2)

Giorgi Jambazishvili
Giorgi Jambazishvili

Reputation: 743

UPDATED Based on my experience when you write event binding in the plain tags, like you have, it won't bind. There are 2 solutions, which I'll cover step by step:

1) bind on document ready. Also please note that I am binding using class, not id, so you have to change your html also

HTML button would look like this:

{% for comentario in objects %}
   {% if user.is_authenticated %}
       <button id="likes-{{forloop.counter0}}" data-comid="{{comentario.id}} class="btn btn-warning btn-sm btn-like" type="button">
...(continue as you have)

ajax.js file would look like this:

$(document).ready(function () {
    $(".btn-like").on("click", function (event) {
        let comid = $(this).attr("data-comid");
        $.get("/home/like/", {"comentario_id": comid}, function (data, status) {
            $(this).hide();
        });
     });
)};

2) The second solution is to bind function call directly in the HTML, I will only write button definition:

<button id="likes-{{forloop.counter0}}" class="btn btn-warning btn-sm" type="button" onclick="likeThisComment('{{comentario.id}}')>
...(continue as you have)

in this HTML you will notice that I've removed class (".likes") and also "data-comid" attribute, since onclick I directly pass them to the function as argument.

ajax.js file

function likeThisComment (comid) {
    $.get("/home/like/", {"comentario_id": comid}, function (data, status) {
        $(this).hide();
    });
}

hope this makes things lot clear. and don't forget to take a look to this tutorial: which has good examples

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599630

There are a few things wrong here. The biggest problem is that it's not valid in HTML to have multiple elements with the same ID; but you are assigning every div in your loop the id likes. You should add that to the list of classes and bind your jQuery even to .likes instead.

Upvotes: 1

Related Questions