Advertisement
Ahmed_Negm

Untitled

Feb 15th, 2024
1,247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.91 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>POST Request Example</title>
  7. </head>
  8. <body>
  9.  
  10.     <h2>Submit Data to Backend</h2>
  11.    
  12.     <form id="myForm">
  13.         <label for="input1">Field 1:</label>
  14.         <input type="text" id="input1" name="input1" required><br><br>
  15.        
  16.         <label for="input2">Field 2:</label>
  17.         <input type="text" id="input2" name="input2" required><br><br>
  18.        
  19.         <button type="submit">Submit</button>
  20.     </form>
  21.  
  22.     <script>
  23.         document.getElementById("myForm").addEventListener("submit", function(event) {
  24.             event.preventDefault(); // Prevent the form from submitting normally
  25.            
  26.             // Get the form data
  27.             const formData = new FormData(this);
  28.            
  29.             // Convert form data to JSON
  30.             const jsonData = {};
  31.             formData.forEach((value, key) => {
  32.                 jsonData[key] = value;
  33.             });
  34.            
  35.             // Send POST request to backend
  36.             fetch('http://example.com/api/endpoint', {
  37.                 method: 'POST',
  38.                 headers: {
  39.                     'Content-Type': 'application/json'
  40.                 },
  41.                 body: JSON.stringify(jsonData)
  42.             })
  43.             .then(response => {
  44.                 if (!response.ok) {
  45.                     throw new Error('Network response was not ok');
  46.                 }
  47.                 return response.json();
  48.             })
  49.             .then(data => {
  50.                 console.log('POST request successful:', data);
  51.                 // Handle response as needed
  52.             })
  53.             .catch(error => {
  54.                 console.error('Error sending POST request:', error);
  55.                 // Handle error
  56.             });
  57.         });
  58.     </script>
  59.  
  60. </body>
  61. </html>
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement