|
| 1 | +document.addEventListener('DOMContentLoaded', () => { |
| 2 | + const videoContainer = document.querySelector('.video-container'); |
| 3 | + const videoForm = document.getElementById('video-form'); |
| 4 | + |
| 5 | + async function fetchVideos() { |
| 6 | + try { |
| 7 | + const response = await fetch('/api/drinking_water_videos'); |
| 8 | + if (!response.ok) { |
| 9 | + throw new Error(`HTTP error! status: ${response.status}`); |
| 10 | + } |
| 11 | + const videos = await response.json(); |
| 12 | + displayVideos(videos); |
| 13 | + } catch (error) { |
| 14 | + videoContainer.innerHTML = `<p>Error fetching videos: ${error.message}</p>`; |
| 15 | + } |
| 16 | + } |
| 17 | + |
| 18 | + function displayVideos(videos) { |
| 19 | + if (videos.length === 0) { |
| 20 | + videoContainer.innerHTML = '<p>No videos to display.</p>'; |
| 21 | + return; |
| 22 | + } |
| 23 | + let html = ''; |
| 24 | + videos.forEach(video => { |
| 25 | + const embedUrl = video.url.includes('youtube.com/watch?v=') |
| 26 | + ? video.url.replace('watch?v=', 'embed/') |
| 27 | + : video.url; |
| 28 | + |
| 29 | + html += ` |
| 30 | + <div class="video-item"> |
| 31 | + <iframe src="${embedUrl}" frameborder="0" allowfullscreen></iframe> |
| 32 | + <div class="video-item-title">${video.title}</div> |
| 33 | + </div> |
| 34 | + `; |
| 35 | + }); |
| 36 | + videoContainer.innerHTML = html; |
| 37 | + } |
| 38 | + |
| 39 | + videoForm.addEventListener('submit', async (event) => { |
| 40 | + event.preventDefault(); |
| 41 | + |
| 42 | + const titleInput = document.getElementById('video-title'); |
| 43 | + const urlInput = document.getElementById('video-url'); |
| 44 | + const errorMessage = document.getElementById('error-message'); |
| 45 | + |
| 46 | + errorMessage.textContent = ''; |
| 47 | + |
| 48 | + let videoUrl = urlInput.value; |
| 49 | + if (videoUrl.includes('youtube.com/watch?v=')) { |
| 50 | + videoUrl = videoUrl.replace('watch?v=', 'embed/'); |
| 51 | + } |
| 52 | + |
| 53 | + const newVideo = { |
| 54 | + title: titleInput.value, |
| 55 | + url: videoUrl, |
| 56 | + }; |
| 57 | + |
| 58 | + try { |
| 59 | + const response = await fetch('/api/drinking_water_videos', { |
| 60 | + method: 'POST', |
| 61 | + headers: { |
| 62 | + 'Content-Type': 'application/json', |
| 63 | + }, |
| 64 | + body: JSON.stringify(newVideo), |
| 65 | + }); |
| 66 | + |
| 67 | + if (!response.ok) { |
| 68 | + const errorData = await response.json(); |
| 69 | + throw new Error(errorData.error || `HTTP error! status: ${response.status}`); |
| 70 | + } |
| 71 | + |
| 72 | + titleInput.value = ''; |
| 73 | + urlInput.value = ''; |
| 74 | + |
| 75 | + fetchVideos(); // Refresh the list of videos |
| 76 | + } catch (error) { |
| 77 | + console.error('Failed to submit video:', error); |
| 78 | + errorMessage.textContent = `Error: ${error.message}`; |
| 79 | + } |
| 80 | + }); |
| 81 | + |
| 82 | + fetchVideos(); |
| 83 | +}); |
0 commit comments