const form = document.getElementById('chat-form'); const userInput = document.getElementById('user-input'); const chatMessages = document.querySelector('.chat-messages'); form.addEventListener('submit', e => { e.preventDefault(); const message = userInput.value; appendMessage('user', message); sendToServer(message); userInput.value = ''; }); function appendMessage(sender, message) { const div = document.createElement('div'); div.classList.add('chat-message', `${sender}-message`); div.innerHTML = `

${message}

`; chatMessages.appendChild(div); chatMessages.scrollTop = chatMessages.scrollHeight; } async function sendToServer(message) { const response = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: message }) }); const data = await response.json(); for (let botMessage of data) { appendMessage('bot', botMessage.text); } }