File size: 1,027 Bytes
e3a7c05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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);
    }
}