67 lines
2.0 KiB
JavaScript
67 lines
2.0 KiB
JavaScript
document.addEventListener('DOMContentLoaded', () => {
|
|
const chatForm = document.getElementById('chat-form');
|
|
const messageInput = document.getElementById('message-input');
|
|
const chatBox = document.getElementById('chat-box');
|
|
|
|
// Load chat history on page load
|
|
function loadChatHistory() {
|
|
if (window.chatHistory && window.chatHistory.length > 0) {
|
|
window.chatHistory.forEach(item => {
|
|
appendMessage(item.message, item.sender);
|
|
});
|
|
}
|
|
}
|
|
|
|
chatForm.addEventListener('submit', async (e) => {
|
|
e.preventDefault();
|
|
|
|
const message = messageInput.value.trim();
|
|
if (!message) return;
|
|
|
|
appendMessage(message, 'user');
|
|
messageInput.value = '';
|
|
|
|
const typingIndicator = appendMessage('Typing...', 'ai');
|
|
|
|
try {
|
|
const response = await fetch('/api/chat.php', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json'
|
|
},
|
|
body: JSON.stringify({ message })
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error('Network response was not ok');
|
|
}
|
|
|
|
const data = await response.json();
|
|
typingIndicator.remove();
|
|
|
|
if(data.error) {
|
|
appendMessage(data.error, 'ai');
|
|
} else {
|
|
appendMessage(data.reply, 'ai');
|
|
}
|
|
|
|
} catch (error) {
|
|
typingIndicator.remove();
|
|
appendMessage('Sorry, something went wrong.', 'ai');
|
|
console.error('Error:', error);
|
|
}
|
|
});
|
|
|
|
function appendMessage(message, sender) {
|
|
const messageElement = document.createElement('div');
|
|
messageElement.classList.add('chat-message', `${sender}-message`);
|
|
messageElement.textContent = message;
|
|
chatBox.appendChild(messageElement);
|
|
chatBox.scrollTop = chatBox.scrollHeight;
|
|
return messageElement;
|
|
}
|
|
|
|
// Initial load
|
|
loadChatHistory();
|
|
});
|