Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>POST Request Example</title>
- </head>
- <body>
- <h2>Submit Data to Backend</h2>
- <form id="myForm">
- <label for="input1">Field 1:</label>
- <input type="text" id="input1" name="input1" required><br><br>
- <label for="input2">Field 2:</label>
- <input type="text" id="input2" name="input2" required><br><br>
- <button type="submit">Submit</button>
- </form>
- <script>
- document.getElementById("myForm").addEventListener("submit", function(event) {
- event.preventDefault(); // Prevent the form from submitting normally
- // Get the form data
- const formData = new FormData(this);
- // Convert form data to JSON
- const jsonData = {};
- formData.forEach((value, key) => {
- jsonData[key] = value;
- });
- // Send POST request to backend
- fetch('http://example.com/api/endpoint', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(jsonData)
- })
- .then(response => {
- if (!response.ok) {
- throw new Error('Network response was not ok');
- }
- return response.json();
- })
- .then(data => {
- console.log('POST request successful:', data);
- // Handle response as needed
- })
- .catch(error => {
- console.error('Error sending POST request:', error);
- // Handle error
- });
- });
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement