141141< body >
142142 < h1 > Scratch Coding Hut Wiki</ h1 >
143143
144+ <!-- Create Wiki Form -->
144145 < div class ="form-container ">
145146 < h2 > Create a Wiki Post</ h2 >
146147 < form id ="createWikiForm ">
@@ -150,6 +151,7 @@ <h2>Create a Wiki Post</h2>
150151 </ form >
151152 </ div >
152153
154+ <!-- Display Wiki Posts -->
153155 < div class ="wikis-container ">
154156 < h2 > Wiki Posts</ h2 >
155157 < ul id ="wikiList "> </ ul >
@@ -160,6 +162,7 @@ <h2>Wiki Posts</h2>
160162 const username = localStorage . getItem ( 'username' ) ;
161163 const backendUrl = 'https://thejsurlback.onrender.com/api' ; // Replace with your backend URL
162164 const wikiList = document . getElementById ( 'wikiList' ) ;
165+ const createWikiForm = document . getElementById ( 'createWikiForm' ) ;
163166
164167 // Fetch and display all wikis
165168 const fetchWikis = async ( ) => {
@@ -177,6 +180,44 @@ <h3><a href="https://thejsurlback.onrender.com/wiki/${encodeURIComponent(wiki.ti
177180 } ) ;
178181 } ;
179182
183+ // Create a new wiki post
184+ createWikiForm . addEventListener ( 'submit' , async ( e ) => {
185+ e . preventDefault ( ) ; // Prevent the default form submission
186+
187+ const title = document . getElementById ( 'wikiTitle' ) . value ;
188+ const content = document . getElementById ( 'wikiContent' ) . value ;
189+ fetch ( 'https://api.ipify.org?format=json' )
190+ . then ( response => response . json ( ) )
191+ . then ( data => {
192+ const ip = data . ip ;
193+ // Use the IP as needed
194+ console . log ( ip ) ; // You can remove the console.log if you don't want to display the IP
195+ } ) ;
196+
197+ const newWiki = {
198+ title,
199+ content,
200+ owner : username || ip , // Assuming the current user is stored in localStorage
201+ } ;
202+
203+ const response = await fetch ( `${ backendUrl } /wikis` , {
204+ method : 'POST' ,
205+ headers : {
206+ 'Content-Type' : 'application/json' ,
207+ } ,
208+ body : JSON . stringify ( newWiki ) ,
209+ } ) ;
210+
211+ if ( response . ok ) {
212+ alert ( 'Wiki post created successfully!' ) ;
213+ fetchWikis ( ) ; // Refresh the list of wiki posts
214+ document . getElementById ( 'wikiTitle' ) . value = '' ;
215+ document . getElementById ( 'wikiContent' ) . value = '' ;
216+ } else {
217+ alert ( 'Error creating wiki post' ) ;
218+ }
219+ } ) ;
220+
180221 // Initial fetch of wikis
181222 fetchWikis ( ) ;
182223 </ script >
0 commit comments