mini-project / script.js
Rohit Ghosh
something
535fb1f
async function sendMessage() {
const userInput = document.getElementById("user-input");
const message = userInput.value;
if (message.trim() === "") return;
displayMessage("You: " + message, "user-message");
userInput.value = "";
// Send message to the server
const response = await fetch("/get_response", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message }),
});
// Check if the response is okay
try {
const jsonResponse = await response.json();
// Display the bot's response in the chatbox
document.getElementById(
"chatbox"
).value += `Bot: ${jsonResponse.response}\n`;
// Also display the message using displayMessage function
displayMessage("Bot: " + jsonResponse.response, "bot-message");
} catch (error) {
console.error("Failed to parse JSON:", error);
document.getElementById(
"chat-log"
).value += `Bot: Something went wrong. Please try again.\n`;
}
}
function displayMessage(text, className) {
const chatLog = document.getElementById("chat-log");
const messageElement = document.createElement("div");
messageElement.className = className;
messageElement.textContent = text;
chatLog.appendChild(messageElement);
chatLog.scrollTop = chatLog.scrollHeight;
}