Spaces:
Runtime error
Runtime error
File size: 3,012 Bytes
b32ac0d |
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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#chat-container {
max-width: 600px;
margin: auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #f9f9f9;
}
#chat-history {
height: 400px;
overflow-y: auto;
margin-bottom: 10px;
border: 1px solid #ddd;
padding: 10px;
background: white;
}
#user-input {
width: calc(100% - 90px);
}
button {
padding: 10px;
}
</style>
<title>Chat Interface</title>
</head>
<body>
<div id="chat-container">
<div id="chat-history"></div>
<input type="text" id="user-input" placeholder="Type your message..." aria-label="Message input">
<button id="send-button" aria-label="Send message">Send</button>
</div>
<script>
document.getElementById("send-button").addEventListener("click", sendMessage);
document.getElementById("user-input").addEventListener("keypress", function(event) {
if (event.key === "Enter") {
event.preventDefault(); // Prevent form submission
sendMessage();
}
});
async function sendMessage() {
const input = document.getElementById("user-input");
const message = input.value.trim();
if (message === "") {
return; // Do not send empty messages
}
// Add user message to chat history
addMessage("User", message);
// Clear input field
input.value = "";
try {
// Send message to the backend
const response = await fetch("/chat/", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ message })
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
addMessage("Bot", data.response);
} catch (error) {
console.error('Error:', error);
addMessage("Bot", "Sorry, something went wrong.");
}
}
function addMessage(sender, message) {
const chatHistory = document.getElementById("chat-history");
const messageElement = document.createElement("div");
messageElement.innerHTML = `<strong>${sender}:</strong> ${message}`;
chatHistory.appendChild(messageElement);
chatHistory.scrollTop = chatHistory.scrollHeight; // Scroll to the bottom
}
</script>
</body>
</html>
|