ayush2917 commited on
Commit
a417d67
·
verified ·
1 Parent(s): 7596470

Update static/js/chat.js

Browse files
Files changed (1) hide show
  1. static/js/chat.js +50 -3
static/js/chat.js CHANGED
@@ -1,4 +1,51 @@
1
- // static/js/chat.js
2
- document.addEventListener('DOMContentLoaded', function () {
3
- console.log('Chat page loaded');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  });
 
1
+ document.addEventListener('DOMContentLoaded', () => {
2
+ const chatForm = document.querySelector('.chat-input');
3
+ const chatInput = chatForm.querySelector('input');
4
+ const chatHistory = document.querySelector('.chat-history');
5
+
6
+ if (chatForm && chatInput && chatHistory) {
7
+ chatForm.addEventListener('submit', (event) => {
8
+ event.preventDefault();
9
+ const message = chatInput.value.trim();
10
+ if (!message) return;
11
+
12
+ // Add user message
13
+ addMessage(message, 'manavi');
14
+ chatInput.value = '';
15
+
16
+ // Send message via AJAX
17
+ const formData = new FormData();
18
+ formData.append('message', message);
19
+
20
+ fetch('/chat', {
21
+ method: 'POST',
22
+ body: formData
23
+ })
24
+ .then(response => response.json())
25
+ .then(data => {
26
+ if (data.reply) {
27
+ addMessage(data.reply, 'krishna');
28
+ scrollToBottom();
29
+ } else {
30
+ addMessage('Hare Manavi! Something went wrong—try again!', 'krishna');
31
+ }
32
+ })
33
+ .catch(error => {
34
+ console.error('Error sending message:', error);
35
+ addMessage('Hare Manavi! The flute’s tune got lost—try again!', 'krishna');
36
+ });
37
+ });
38
+ }
39
+
40
+ function addMessage(text, sender) {
41
+ const messageDiv = document.createElement('div');
42
+ messageDiv.className = `message ${sender}`;
43
+ messageDiv.textContent = text;
44
+ chatHistory.appendChild(messageDiv);
45
+ messageDiv.style.animation = 'slideIn 0.5s ease';
46
+ }
47
+
48
+ function scrollToBottom() {
49
+ chatHistory.scrollTop = chatHistory.scrollHeight;
50
+ }
51
  });