Skip to content

Instantly share code, notes, and snippets.

@lmzach09
Created September 1, 2019 17:18
Show Gist options
  • Save lmzach09/28aafd06517c2d58dc463cadc09d549b to your computer and use it in GitHub Desktop.
Save lmzach09/28aafd06517c2d58dc463cadc09d549b to your computer and use it in GitHub Desktop.
JS for a ChatBot web page
const submitButton = document.getElementById('submitButton');
const chatbotInput = document.getElementById('chatbotInput');
const chatbotOutput = document.getElementById('chatbotOutput');
submitButton.onclick = userSubmitEventHandler;
chatbotInput.onkeyup = userSubmitEventHandler;
function userSubmitEventHandler(event) {
if (
(event.keyCode && event.keyCode === 13) ||
event.type === 'click'
) {
chatbotOutput.innerText = 'thinking...';
askChatBot(chatbotInput.value);
}
}
function askChatBot(userInput) {
const myRequest = new Request('/', {
method: 'POST',
body: userInput
});
fetch(myRequest).then(function(response) {
if (!response.ok) {
throw new Error('HTTP error, status = ' + response.status);
} else {
return response.text();
}
}).then(function(text) {
chatbotInput.value = '';
chatbotOutput.innerText = text;
}).catch((err) => {
console.error(err);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment