ayush2917 commited on
Commit
394707d
·
verified ·
1 Parent(s): a38822d

Update static/js/chat.js

Browse files
Files changed (1) hide show
  1. static/js/chat.js +49 -0
static/js/chat.js CHANGED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ document.addEventListener('DOMContentLoaded', () => {
2
+ const chatForm = document.getElementById('chat-form');
3
+ const chatMessages = document.getElementById('chat-messages');
4
+ const messageInput = document.getElementById('message-input');
5
+ const comicButton = document.getElementById('comic-button');
6
+ const comicStrip = document.getElementById('comic-strip');
7
+
8
+ chatForm.addEventListener('submit', async (e) => {
9
+ e.preventDefault();
10
+ const message = messageInput.value;
11
+ chatMessages.innerHTML += `<p><strong>You:</strong> ${message}</p>`;
12
+ messageInput.value = '';
13
+
14
+ try {
15
+ const response = await fetch('/chat', {
16
+ method: 'POST',
17
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
18
+ body: `message=${encodeURIComponent(message)}`
19
+ });
20
+ const data = await response.json();
21
+ chatMessages.innerHTML += `<p><strong>Krishna:</strong> ${data.reply}</p>`;
22
+ chatMessages.scrollTop = chatMessages.scrollHeight;
23
+
24
+ // Auto-trigger comic strip if user asks for a story
25
+ if (message.toLowerCase().includes('story')) {
26
+ fetchComicStrip();
27
+ }
28
+ } catch (error) {
29
+ console.error('Error sending message:', error);
30
+ chatMessages.innerHTML += `<p><strong>Error:</strong> Couldn’t reach Krishna—try again!</p>`;
31
+ chatMessages.scrollTop = chatMessages.scrollHeight;
32
+ }
33
+ });
34
+
35
+ comicButton.addEventListener('click', fetchComicStrip);
36
+
37
+ async function fetchComicStrip() {
38
+ try {
39
+ const response = await fetch('/comic');
40
+ const data = await response.json();
41
+ comicStrip.innerHTML = data.comic_images.map(url =>
42
+ `<img src="${url}" alt="Krishna Comic Panel">`
43
+ ).join('');
44
+ } catch (error) {
45
+ console.error('Error fetching comic strip:', error);
46
+ comicStrip.innerHTML = `<p>Error loading comic strip—try again!</p>`;
47
+ }
48
+ }
49
+ });