40 lines
1.4 KiB
JavaScript
40 lines
1.4 KiB
JavaScript
document.addEventListener('DOMContentLoaded', () => {
|
|
const chatForm = document.getElementById('chat-form');
|
|
const chatInput = document.getElementById('chat-input');
|
|
const chatMessages = document.getElementById('chat-messages');
|
|
|
|
const appendMessage = (text, sender) => {
|
|
const msgDiv = document.createElement('div');
|
|
msgDiv.classList.add('message', sender);
|
|
msgDiv.textContent = text;
|
|
chatMessages.appendChild(msgDiv);
|
|
chatMessages.scrollTop = chatMessages.scrollHeight;
|
|
};
|
|
|
|
chatForm.addEventListener('submit', async (e) => {
|
|
e.preventDefault();
|
|
const message = chatInput.value.trim();
|
|
if (!message) return;
|
|
|
|
appendMessage(message, 'visitor');
|
|
chatInput.value = '';
|
|
|
|
try {
|
|
const response = await fetch('api/chat.php', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ message })
|
|
});
|
|
const data = await response.json();
|
|
|
|
// Artificial delay for realism
|
|
setTimeout(() => {
|
|
appendMessage(data.reply, 'bot');
|
|
}, 500);
|
|
} catch (error) {
|
|
console.error('Error:', error);
|
|
appendMessage("Sorry, something went wrong. Please try again.", 'bot');
|
|
}
|
|
});
|
|
});
|