Using with AJAX

  1. Basic example with vanilla JS
  2. File uploads with AJAX
  3. Using jQuery

AJAX is a good option if you don't want to redirect your users after submission or if you want to add custom validation logic, that can't be performed by HTML Validations.

Basic example with vanilla JS

Let's suppose there is a following form:

<form action="" id="contact-form" method="POST" accept-charset="UTF-8">
  <input type="text" name="name">
  <input type="email" name="email">

  <button type="submit">Send</button>

  <div id="submit-result"></div>

In this case it is only needed to paste this example code below anywhere before the </body> tag:

<script type="text/javascript">
  var form = document.getElementById("contact-form");

  var submitResult = document.getElementById("submit-result");

  form.onsubmit = function(e) {

    var formData = new FormData(form);
    var xhr = new XMLHttpRequest();"POST", form.action, true);

    xhr.onload = function(e) {
      var response = JSON.parse(xhr.response);

      if (xhr.status === 200) {
        submitResult.innerHTML = "Success";
      } else {
        submitResult.innerHTML = "Error: " + response.error;


File uploads with AJAX

The above code will still work if your form performs file uploads.

<form action="" id="contact-form" method="POST" accept-charset="UTF-8">
  <input type="file" name="attachment" placeholder="Your Attachment">

Using jQuery

For the same form from the previous example the following code is needed to be placed before the </body> tag:

<script type="text/javascript">
  $("#new_demo_form").on("submit", function(e) {

    var $form = $(this);
    var $submitResult = $("#submit-result");

    var payload = {};
    $form.serializeArray().map((field) => { payload[] = field.value});

      type: "POST",
      url: $form.attr("action"),
      data: payload,
      dataType: "json",
      success: function() { $submitResult.text("Success"); },
      error: function(response) { $submitResult.text("Error: " + response.error); }