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?
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
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.