TIST-37: Send ajax request to add favorite #27

Merged
steve_dekart merged 2 commits from TIST-37 into develop 2025-07-02 22:35:07 +02:00
3 changed files with 57 additions and 2 deletions

View File

@ -11,6 +11,8 @@ the_header(
);
?>
<div id="recipe-id" hidden><?= $context['recipe']->get_id() ?></div>
<div class="container">
<div class="single-recipe">
<div class="single-recipe-info">
@ -72,8 +74,8 @@ the_header(
</div>
</div>
<div class="small-btns">
<button class="btn btn-secondary btn-small hover-anim" title="Add To Favorites">
<i class="fa-regular fa-heart"></i>
<button id="favorite-btn" class="btn btn-secondary btn-small hover-anim <?= $context['recipe']->is_in_favorite ? 'active' : '' ?>" title="Add To Favorites">
<i class="<?= $context['recipe']->is_in_favorite ? 'fa-solid' : 'fa-regular' ?> fa-heart"></i>
</button>
<a class="btn btn-secondary btn-small hover-anim"
href="<?php the_permalink('recipes:export-pdf', [$context['recipe']->get_id()]); ?>"

View File

@ -92,6 +92,15 @@ body {
.logo {
max-width: 70px;
}
.toastify.info {
background: #003a92;
}
.toastify.error {
background: #770000;
}
.toastify.success {
background: #00660f;
}
/*placeholder for search and login section*/
.search-and-login {
@ -638,6 +647,9 @@ hr {
display: inline-block;
text-align: center;
}
.btn:disabled {
opacity: 0.3;
}
.btn-primary {
background-color: var(--button-primary);

View File

@ -1,3 +1,4 @@
const recipeId = document.getElementById('recipe-id').textContent;
const toggleBtn = document.getElementById('day-select');
const dropdown = document.getElementById('custom-select-dropdown');
@ -69,3 +70,43 @@ document.addEventListener('click', (e) =>{
overlay.classList.add("hidden");
}
});
const favoriteBtn = document.getElementById('favorite-btn');
const favoriteIcon = favoriteBtn.querySelector('i');
favoriteBtn.addEventListener('click', async (e) => {
const isFavorite = favoriteBtn.classList.contains('active');
const type = isFavorite ? 'remove' : 'add';
const formData = new FormData();
formData.append('action', 'favorites');
formData.append('recipe_id', recipeId);
formData.append('type', type);
favoriteBtn.disabled = true;
const response = await fetch('/ajax', {
method: 'POST',
body: formData
});
favoriteBtn.disabled = false;
const json = await response.json();
if(!response.ok) {
const message = json.error;
showToastify(message, 'error');
return;
}
favoriteBtn.classList.toggle('active');
if(type == 'add') {
favoriteIcon.classList.remove('fa-regular');
favoriteIcon.classList.add('fa-solid');
} else {
favoriteIcon.classList.add('fa-regular');
favoriteIcon.classList.remove('fa-solid');
}
showToastify(json.success, 'success');
});