0

So I am trying to create my own custom like button with ajax but there is one problem, when I press the like button I should reload the page in order to see my upvote. I want to do it without reloading the page.

here is the code:

article.html

{% block content %}
<div>
    {% for a in article %}
    [... unrelated html ...]

    <p><input type="button" class="like" id="{{ a.id }}" value="Like" /></p>
    <p id="count{{ a.id }}">{{ a.total_likes }}</p>
    </div>
    {% endfor %}

</div>
<script>

$('.like').click(function(){

      $.ajax({
               type: "POST",
               url: "{% url 'like_button' %}",
               data: {'pk': $(this).attr('id'), 'csrfmiddlewaretoken': '{{ csrf_token }}'},
               dataType: "json",
               success: function(response) {
                      var pk = $(this).attr('id');
                      $('#count' + pk).html(response.likes_count) #change the html when success. response.likes_count is connected to python, it indicates the number of counts on the query.
                },
               error: function(rs, e) {
                      alert(rs.responseText);
               }
          });
    })

</script>
{% endblock %}

What should I do in order to reslove this issue?

1 Answer 1

2

Inside success callback this doesn't point to DOM element

$('.like').click(function(){
  var pk = $(this).attr('id'); // Get your id here
  // Whole ajax stuff
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.