| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- 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 = `
- <span class="user">${msg.username}:</span> ${msg.message_text || ''}
- ${msg.is_image ? `<img src="${msg.attachment_path}" alt="Image">` : ''}
- ${!msg.is_image && msg.attachment_path ? `<a href="${msg.attachment_path}" download>Download Attachment</a>` : ''}
- <small>${msg.created_at}</small>
- `;
- 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);
- }
- });
- });
- });
|