65 lines
2.3 KiB
JavaScript
65 lines
2.3 KiB
JavaScript
document.addEventListener('DOMContentLoaded', () => {
|
|
const chatForm = document.getElementById('chat-form');
|
|
const messageInput = document.getElementById('message-input');
|
|
const messagesContainer = document.querySelector('.messages');
|
|
|
|
chatForm.addEventListener('submit', (e) => {
|
|
e.preventDefault();
|
|
const messageText = messageInput.value.trim();
|
|
if (messageText === '') return;
|
|
|
|
appendMessage('user', messageText);
|
|
messageInput.value = '';
|
|
showTypingIndicator();
|
|
|
|
fetch('/api/chat.php', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
},
|
|
body: `message=${encodeURIComponent(messageText)}`
|
|
})
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
removeTypingIndicator();
|
|
if (data.reply) {
|
|
appendMessage('bot', data.reply);
|
|
}
|
|
})
|
|
.catch(error => {
|
|
removeTypingIndicator();
|
|
appendMessage('bot', 'Sorry, something went wrong. Please try again.');
|
|
console.error('Error:', error);
|
|
});
|
|
});
|
|
|
|
function appendMessage(role, text) {
|
|
const messageElement = document.createElement('div');
|
|
messageElement.classList.add('message', role);
|
|
|
|
const contentElement = document.createElement('div');
|
|
contentElement.classList.add('message-content');
|
|
contentElement.textContent = text;
|
|
|
|
messageElement.appendChild(contentElement);
|
|
messagesContainer.appendChild(messageElement);
|
|
messagesContainer.scrollTop = messagesContainer.scrollHeight;
|
|
}
|
|
|
|
function showTypingIndicator() {
|
|
const typingIndicator = document.createElement('div');
|
|
typingIndicator.id = 'typing-indicator';
|
|
typingIndicator.classList.add('message', 'typing');
|
|
typingIndicator.textContent = 'EvolveX is typing...';
|
|
messagesContainer.appendChild(typingIndicator);
|
|
messagesContainer.scrollTop = messagesContainer.scrollHeight;
|
|
}
|
|
|
|
function removeTypingIndicator() {
|
|
const typingIndicator = document.getElementById('typing-indicator');
|
|
if (typingIndicator) {
|
|
typingIndicator.remove();
|
|
}
|
|
}
|
|
});
|