0 I followed a solution on how to get Django Like and Unlike button not to reload the page on click. The solution i found works but only with TEXT toggle (Like and Unlike) and i want an Icon Toggle (Like and Unlike Icon).
I am new to Django Backend and Ajax, i will be happy if someone can help on how to deal with this. Thanks in Advance.
$( document ).ready(function() {
$('.like-form').submit(function(e){
e.preventDefault()
const post_id = $(this).attr('id')
const likeText = $(`.like-btn${post_id}`).text()
const trim = $.trim(likeText)
const url = $(this).attr('action')
let res;
const likes = $(`.like-count${post_id}`).text()
const trimCount = parseInt(likes)
$.ajax({
type: 'POST',
url: url,
data: {
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
'post_id':post_id,
},
success: function(response) {
if(trim === 'Unlike') {
$(`.like-btn${post_id}`).text('Like')
res = trimCount - 1
} else {
$(`.like-btn${post_id}`).text('Unlike')
res = trimCount + 1
}
$(`.like-count${post_id}`).text(res)
},
error: function(response) {
console.log('error', response)
}
})
});
});
<!-- Like Button -->
<li class="list-inline-item">
<form action="{% url 'posts:like-post-view' %}" method="POST" class='like-form' id='{{obj.id}}'>
{% csrf_token %}
<input type="hidden" name="post_id" value={{obj.id}}>
<button type="submit" class="btn btn-link g-color-gray-dark-v5 g-color-red--hover text-red p-0 border-0 btn-outline-light like-btn{{obj.id}}">
{% if user not in obj.liked.all %}
Like
<i class="align-middle mr-1 icon-heart u-line-icon-pro g-font-size-25"></i>
{% else %}
Unlike
<i class="align-middle mr-1 icon-like u-line-icon-pro g-font-size-25"></i>
{% endif %}
</button>
<span class="g-color-gray-dark-v5 g-font-size-15 like-count{{obj.id}}"> {{obj.num_likes}}</span>
</form>
</li>
<!-- End Like Button -->