Use ajax for like button

This commit is contained in:
Nyymix 2025-04-21 16:37:06 +03:00
parent 13fdbe4f4a
commit 47b543bbb3
3 changed files with 75 additions and 24 deletions

View file

@ -81,19 +81,16 @@
</div>
<div class="uk-grid-small" uk-grid>
<div class="uk-width-expand" uk-leader>Likes</div>
<div>{{ photo.likes }}</div>
<div id="like-count">{{ photo.likes }}</div>
</div>
<div class="uk-grid-small" uk-grid>
<div class="uk-width-expand" uk-leader>Download photo</div>
<div><a href="{{ photo.photo.url }}">{{ photo.width }}x{{ photo.height }}</a></div>
</div>
<div class="uk-grid-small" uk-grid>
<form action="{% url 'gallery:photo_url' photo.album.slug photo.slug %}" method="POST" class="uk-form">
{% csrf_token %}
<button type="submit" name="like" value="true" class="uk-button uk-button-primary">
<span uk-icon="icon: heart"></span> Like
<button id="like-button" class="uk-button uk-button-primary">
<span id="heart-icon" uk-icon="icon: heart"></span> <span id="like-text">Like</span>
</button>
</form>
</div>
</div>
</div>
@ -137,11 +134,46 @@
</div>
</div>
</div>
<script>
const likeBtn = document.getElementById('like-button');
const likeText = document.getElementById('like-text');
const heartIcon = document.getElementById('heart-icon');
const likeCount = document.getElementById('like-count');
likeBtn.addEventListener('click', function () {
fetch("{% url 'gallery:photo_like_url' photo.album.slug photo.slug %}", {
method: "POST",
headers: {
"X-CSRFToken": "{{ csrf_token }}",
"Content-Type": "application/json",
},
})
.then(response => response.json())
.then(data => {
if (data.success) {
likeCount.innerText = data.likes;
if (data.status === "liked") {
likeText.innerText = "Unlike";
heartIcon.setAttribute("style", "color: red");
} else {
likeText.innerText = "Like";
heartIcon.setAttribute("style", "color: inherit");
}
}
});
});
</script>
{% if liked %}
<script>
document.addEventListener("DOMContentLoaded", function() {
document.getElementById('like-text').innerText = "Unlike";
document.getElementById('heart-icon').setAttribute("style", "color: red");
});
</script>
{% endif %}
{% endblock %}