How to Post Form Data Using JavaScript?

Estimated read time 2 min read

You can post form data using JavaScript with the fetch function or by using the XMLHttpRequest object. Here’s an example of how you can post form data using the fetch function:

let form = document.getElementById("myForm");

form.addEventListener("submit", function(event) {
  event.preventDefault();
  
  let formData = new FormData(form);
  
  fetch("https://example.com/api/submit-form", {
    method: "POST",
    body: formData
  })
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
});

In this example, we first get a reference to the form using its id attribute.

Next, we add an event listener to the form’s submit event. This will be triggered when the user submits the form.

Inside the event listener, we prevent the default form submit behavior using event.preventDefault().

We then create a new FormData object from the form, which will contain all the form data.

Finally, we use the fetch function to send a POST request to the server, passing the form data in the body of the request.

The response from the server is expected to be JSON, so we use response.json() to parse the response and extract the JSON data.

This is just a basic example, and you can modify it to suit your needs, such as handling errors or displaying a message to the user after the form has been submitted.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply