script.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. document.addEventListener('DOMContentLoaded', () => {
  2. const form = document.getElementById('chat-form');
  3. const refreshBtn = document.getElementById('refresh-btn');
  4. const chatWindow = document.getElementById('chat-window');
  5. // Function to fetch and display messages
  6. function fetchMessages() {
  7. fetch('api/fetch_messages.php')
  8. .then(response => response.json())
  9. .then(messages => {
  10. chatWindow.innerHTML = '';
  11. messages.forEach(msg => {
  12. const div = document.createElement('div');
  13. div.classList.add('message');
  14. div.innerHTML = `
  15. <span class="user">${msg.username}:</span> ${msg.message_text || ''}
  16. ${msg.is_image ? `<img src="${msg.attachment_path}" alt="Image">` : ''}
  17. ${!msg.is_image && msg.attachment_path ? `<a href="${msg.attachment_path}" download>Download Attachment</a>` : ''}
  18. <small>${msg.created_at}</small>
  19. `;
  20. chatWindow.appendChild(div);
  21. });
  22. chatWindow.scrollTop = chatWindow.scrollHeight; // Auto-scroll to bottom
  23. });
  24. }
  25. // Initial load
  26. fetchMessages();
  27. // Auto-poll every 5 seconds for real-time updates
  28. setInterval(fetchMessages, 5000);
  29. // Manual refresh button (still available)
  30. refreshBtn.addEventListener('click', fetchMessages);
  31. // Send message
  32. form.addEventListener('submit', (e) => {
  33. e.preventDefault();
  34. const formData = new FormData(form);
  35. fetch('api/send_message.php', {
  36. method: 'POST',
  37. body: formData
  38. })
  39. .then(response => response.json())
  40. .then(result => {
  41. if (result.success) {
  42. form.reset();
  43. fetchMessages(); // Auto-refresh after send
  44. } else {
  45. alert(result.error);
  46. }
  47. });
  48. });
  49. });