JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Form Submission</title>
</head>
<body>
    <div class="form-container">
        <h2>Form Submission</h2>
        <form id="myForm" class='myFormClass'>
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" required>

            <label for="email">Email:</label>
            <input type="email" id="email" name="email" required>

            <label for="message">Message:</label>
            <textarea id="message" name="message" rows="4" cols="50" required></textarea>

            <input type="submit" value="Submit">
        </form>
    </div>
</body>
</html>

CSS

body {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 100vh;
  font-family: Arial, sans-serif;
}

.form-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.form-container label {
  margin-bottom: 10px;
}

.form-container input,
.form-container textarea {
  width: 300px;
  padding: 5px;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  border-radius: 3px;
}

.myFormClass {
  display: flex;
  flex-flow: column wrap;
}

.form-container input[type="submit"] {
  background-color: teal;
  border: 1px solid darkblue;
  color: white;
  cursor: pointer;
  align-self: center;
}

JavaScript

document.getElementById("myForm").addEventListener("submit", function(event) {
  event.preventDefault(); // Prevent form submission

  // Collect form data
  const formData = new FormData(event.target);

  // Convert form data to JSON
  const jsonData = {};
  formData.forEach((value, key) => {
    jsonData[key] = value;
  });

  // Send data to the API
  fetch('https://api.example.com/submit', {
    method: 'POST',
    body: JSON.stringify(jsonData),
    headers: {
      'Content-Type': 'application/json'
    }
  })
    .then(function(response) {
    if (response.ok) {
      // Successful API response
      alert("Form submitted successfully!");
      // Perform any other actions or redirect as needed
    } else {
      // API request failed
      alert("Form submission failed!");
    }
  })
    .catch(function(error) {
    // Network or other errors
    alert("An error occurred while submitting the form.");
    console.error(error);
  });
});