templates/_partials/courses/favorites.js.twig line 1

Open in your IDE?
  1. <script>
  2. /**
  3. * JavaScript para la gestión de favoritos en cursos
  4. */
  5. // Función para inicializar los manejadores de eventos para los favoritos
  6. function initFavoriteHandlers() {
  7. // Seleccionar todos los elementos con la clase favorite-toggle
  8. const favoriteToggles = document.querySelectorAll('.favorite-toggle');
  9. // Añadir evento click a cada elemento
  10. favoriteToggles.forEach(toggle => {
  11. toggle.addEventListener('click', function() {
  12. const type = this.getAttribute('data-type');
  13. const id = this.getAttribute('data-id');
  14. if (id === '0') {
  15. alert('No hay ' + (type === "entidad" ? "entidad colaboradora" : "formador") + ' asociado');
  16. return;
  17. }
  18. // Llamar a la función para alternar el estado de favorito
  19. toggleFavorite(type, id, this);
  20. });
  21. });
  22. }
  23. // Función para alternar el estado de favorito mediante AJAX
  24. function toggleFavorite(type, id, element) {
  25. const tr = element.closest('tr');
  26. const hasFavorite = tr.classList.contains('favorite');
  27. const url = '/ajax/courses/favorite/' + type + '/' + id;
  28. fetch(url, {
  29. method: 'POST',
  30. headers: {
  31. 'Content-Type': 'application/json',
  32. 'X-Requested-With': 'XMLHttpRequest'
  33. }
  34. })
  35. .then(response => response.json())
  36. .then(data => {
  37. if (data.success) {
  38. // Actualizar el estado visual del elemento
  39. if (data.isFavorito) {
  40. tr.classList.add('favorite');
  41. element.setAttribute('title', 'Quitar de favoritos');
  42. element.textContent = "*";
  43. } else {
  44. tr.classList.remove('favorite');
  45. element.setAttribute('title', 'Añadir a favoritos');
  46. element.textContent = "";
  47. }
  48. } else {
  49. // Mostrar mensaje de error
  50. alert(data.message || 'Error al actualizar favorito');
  51. }
  52. })
  53. .catch(error => {
  54. console.error('Error:', error);
  55. alert('Error al procesar la solicitud');
  56. });
  57. }
  58. // Inicializar cuando el DOM esté listo
  59. document.addEventListener('DOMContentLoaded', function() {
  60. // Solo inicializar si el usuario está logueado (verificado en el template)
  61. if (document.body.classList.contains('logged-in')) {
  62. initFavoriteHandlers();
  63. }
  64. });
  65. </script>