keya-560m / static /js /chat.js
dev
Add application file
e3a7c05
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 = `<p>${message}</p>`;
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);
}
}