|
document.addEventListener('DOMContentLoaded', (event) => {
|
|
const chatMessages = document.getElementById('chat-messages');
|
|
const userInput = document.getElementById('user-input');
|
|
const sendButton = document.getElementById('send-button');
|
|
|
|
function addMessage(message, isUser = false) {
|
|
const messageElement = document.createElement('p');
|
|
messageElement.textContent = message;
|
|
messageElement.style.backgroundColor = isUser ? '#e6f2ff' : '#f0f0f0';
|
|
messageElement.style.padding = '10px';
|
|
messageElement.style.borderRadius = '5px';
|
|
messageElement.style.marginBottom = '10px';
|
|
chatMessages.appendChild(messageElement);
|
|
chatMessages.scrollTop = chatMessages.scrollHeight;
|
|
}
|
|
|
|
function sendMessage() {
|
|
const message = userInput.value.trim();
|
|
if (message) {
|
|
addMessage(You: ${message}, true);
|
|
userInput.value = '';
|
|
|
|
fetch('/chatbot', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({ text: message }),
|
|
})
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
if (data.error) {
|
|
addMessage(Error: ${data.error});
|
|
} else {
|
|
addMessage(Chatbot: ${data.response});
|
|
}
|
|
})
|
|
.catch((error) => {
|
|
console.error('Error:', error);
|
|
addMessage('Error: Unable to get response from the server.');
|
|
});
|
|
}
|
|
}
|
|
|
|
sendButton.addEventListener('click', sendMessage);
|
|
userInput.addEventListener('keypress', function (e) {
|
|
if (e.key === 'Enter') {
|
|
sendMessage();
|
|
}
|
|
});
|
|
}); |