1- const chatForm = document . getElementById ( "chat-form" ) ;
2- const chatInput = document . getElementById ( " chat-input" ) ;
3- const chatOutput = document . getElementById ( "chat-output" ) ;
1+ // script.js
2+ document . getElementById ( ' chat-form' ) . addEventListener ( 'submit' , async function ( event ) {
3+ event . preventDefault ( ) ;
44
5- chatForm . addEventListener ( "submit" , async ( e ) => {
6- e . preventDefault ( ) ;
7- const message = chatInput . value . trim ( ) ;
8- if ( ! message ) return ;
5+ const message = document . getElementById ( 'message' ) . value ;
6+ const fileInput = document . getElementById ( 'file' ) ;
7+ const formData = new FormData ( ) ;
98
10- chatOutput . innerHTML += `<p class="user-message">${ message } </p>` ;
11- chatInput . value = "" ;
12- chatOutput . scrollTop = chatOutput . scrollHeight ;
9+ formData . append ( 'message' , message ) ;
10+ if ( fileInput . files . length > 0 ) {
11+ formData . append ( 'file' , fileInput . files [ 0 ] ) ;
12+ }
1313
14- const response = await fetch ( "gptchat.php" , {
15- method : "POST" ,
16- headers : {
17- "Content-Type" : "application/json" ,
18- } ,
19- body : JSON . stringify ( { message } ) ,
14+ const response = await fetch ( 'index.php' , {
15+ method : 'POST' ,
16+ body : formData
2017 } ) ;
2118
22- if ( response . ok ) {
23- const data = await response . json ( ) ;
24- if ( data . choices && data . choices [ 0 ] && data . choices [ 0 ] . text ) {
25- chatOutput . innerHTML += `<p class="bot-message">${ data . choices [ 0 ] . text } </p>` ;
26- } else {
27- console . error ( "Error: Unexpected response format" , data ) ;
28- }
29- chatOutput . scrollTop = chatOutput . scrollHeight ;
30- } else {
31- console . error ( "Error communicating with GPTChat API" ) ;
19+ const result = await response . json ( ) ;
20+ displayMessage ( result . message , result . imageUrl ) ;
21+ } ) ;
22+
23+ function displayMessage ( message , imageUrl ) {
24+ const chatBox = document . getElementById ( 'chat-box' ) ;
25+ const messageDiv = document . createElement ( 'div' ) ;
26+ messageDiv . classList . add ( 'message' ) ;
27+ messageDiv . innerHTML = `<p>${ message } </p>` ;
28+
29+ if ( imageUrl ) {
30+ const img = document . createElement ( 'img' ) ;
31+ img . src = imageUrl ;
32+ messageDiv . appendChild ( img ) ;
3233 }
33- } ) ;
34+
35+ chatBox . appendChild ( messageDiv ) ;
36+ chatBox . scrollTop = chatBox . scrollHeight ;
37+ }
0 commit comments