Submit HTML form using AJAX

Postform can accept submissions through asynchronous HTTP requests. This gives you complete control over handling success and error responses which can greatly improve the user experience for your visitors.

To submit your form using AJAX, set the Accept request header to application/json. Below are some examples using popular AJAX libraries.

Axios

Axios is a promise based HTTP client. Try this example out in CodePen:

<form id="myForm" action="https://postform.com/s/FORM_ID" method="POST">
  <label for="email">Email</label>
  <input id="email" name="email" required />
  <button type="submit">Submit</button>
</form>

<script>
window.addEventListener('load', function () {
  const form = document.getElementById("myForm");
  const actionUrl = form.getAttribute("action");

  form.addEventListener('submit', function (event) {
    event.preventDefault();
    const formData = new FormData(form);

    axios
      .post(actionUrl, formData)
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
  });
});
</script>

jQuery

Use jQuery's ajax function to make an HTTP request. Try this example out in CodePen:

<form id="myForm" action="https://postform.com/s/FORM_ID" method="POST">
  <label for="email">Email</label>
  <input id="email" name="email" required />
  <button type="submit">Submit</button>
</form>

<script>
$(function () {
  $('#myForm').submit(function(event) {
    event.preventDefault();

    var actionUrl = $(this).attr('action');
    var formData = $(this).serialize();

    $.ajax({
      url: actionUrl,
      method: 'POST',
      dataType: 'json',
      data: formData,
      success: function(data) {
        console.log(data);
      },
    });
  });
});
</script>

File Uploading

If your form contains file input fields, FormData can be used to encode the data as multipart/form-data. Try this example out in CodePen:

<form id="myForm" action="https://postform.com/s/FORM_ID" method="POST" enctype="multipart/form-data">
  <label for="files">Files</label>
  <input type="file" id="files" name="files" required multiple />
  <button type="submit">Submit</button>
</form>

<script>
$(function () {
  $('#myForm').submit(function(event) {
    event.preventDefault();

    var actionUrl = $(this).attr('action');
    var formData = new FormData(this);

    $.ajax({
      url: actionUrl,
      method: "POST",
      dataType: "json",
      contentType: false,
      data: formData,
      processData: false,
      success: function(data) {
        alert(data);
      },
    });
  });
});
</script>