JavaScript Coder

Submit a form using post method using Javascript

beginner javascript submit form post method

Submitting a form using the POST method in JavaScript can be done using the Fetch API, which is a newer and simpler way to make HTTP requests. In this tutorial, we’ll go through the steps required to submit a form using the POST method with the Fetch API.

Step 1: Create a Form

First, create an HTML form that includes the inputs you want to send via POST. For example:


<form id="myform">
  <div >
    <label for="myform_name">Name</label>
    <input type="text" name="name" id="myform_name" placeholder="Your Name">
  </div>
  <div >
    <label for="myform_email">Email address:</label>
    <input type="email" name="email" id="myform_email"  placeholder="Your email">
  </div>
  <div class="form-group">
    <label for="myform_message">Message</label>
    <textarea name="message" id="myform_message" rows="3"></textarea>
  </div>
  
  <button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>

This form has input fields for the name and email, a message field, and a submit button.

Step 2: Create a JavaScript Function

Next, create a JavaScript function that will handle the form submission. This function will use the Fetch API to send a POST request to the server.

function submitForm(e) {
  e.preventDefault();

  var myform = document.getElementById("myform");

  var formData = new FormData(myform);

  fetch("https://show.ratufa.io/json", {
    method: "POST",
    body: formData,
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error("network returns error");
      }
      return response.json();
    })
    .then((resp) => {
      let respdiv = document.createElement("pre");
      respdiv.innerHTML = JSON.stringify(resp, null, 2);
      myform.replaceWith(respdiv);
      console.log("resp from server ", resp);
    })
    .catch((error) => {
      // Handle error
      console.log("error ", error);
    });
}

This function creates a new FormData object from the form element with the ID myform. The FormData object contains all the input values from the form.

Then, it calls the fetch() method with the URL to which the request should be sent and an options object that includes the method (“POST”) and the body (the FormData object).

Note that the fetch() method directly does not return the response from the server. The fetch() method returns a Promise, which is handled with the .then() and .catch() methods. The .then() method handles the response from the server, and the .catch() method handles any errors that occur.

In this example, we’re making a GET request to https://show.ratufa.io/json and then handling the response by checking if it’s okay (response.ok) and then parsing the JSON data using the json() method on the response object. This method returns a Promise that resolves to the JSON data.

The service that we use in this example (show.ratufa.io/json) simply responds by sending back the form data it received in JSON format. This service is quite useful for testing form submissions

Once we have the JSON data, we can use it as needed. In this example, we’re just logging it to the console.

Note that the json() method will throw an error if the response is not valid JSON.

Step 3: Wire the Form submit event

Now that we have a function to handle the form submission, we need to call it when the form is submitted. We can do this by adding an event listener to the form’s submit event.

var myform = document.getElementById("myform");

myform.addEventListener("submit", submitForm);

This code adds an event listener to the form element with the ID “myform”. When the form is submitted, it calls the submitForm() function we created in Step 2.

All Code together

See the Pen Submit form using Javascript (using fetch api) .

Try the form above. The form submits to show.ratufa.io and displays the result. You can even tweak the form above and see the results!

See Also