document.addEventListener('DOMContentLoaded', () => { const form = document.getElementById('chat-form'); const refreshBtn = document.getElementById('refresh-btn'); const chatWindow = document.getElementById('chat-window'); // Function to fetch and display messages function fetchMessages() { fetch('api/fetch_messages.php') .then(response => response.json()) .then(messages => { chatWindow.innerHTML = ''; messages.forEach(msg => { const div = document.createElement('div'); div.classList.add('message'); div.innerHTML = ` ${msg.username}: ${msg.message_text || ''} ${msg.is_image ? `Image` : ''} ${!msg.is_image && msg.attachment_path ? `Download Attachment` : ''} ${msg.created_at} `; chatWindow.appendChild(div); }); chatWindow.scrollTop = chatWindow.scrollHeight; // Auto-scroll to bottom }); } // Initial load fetchMessages(); // Auto-poll every 5 seconds for real-time updates setInterval(fetchMessages, 5000); // Manual refresh button (still available) refreshBtn.addEventListener('click', fetchMessages); // Send message form.addEventListener('submit', (e) => { e.preventDefault(); const formData = new FormData(form); fetch('api/send_message.php', { method: 'POST', body: formData }) .then(response => response.json()) .then(result => { if (result.success) { form.reset(); fetchMessages(); // Auto-refresh after send } else { alert(result.error); } }); }); });