Submit forms with JavaScript (AJAX)

The submission via XHR request (formerly called AJAX), allows you to further customize the submission process. This allows you to execute the form submission in the background without reloading the page and to customize the display of messages (success, error) without redirecting to a message page. Furthermore, you can perform any validations to the form inputs in the JavaScript program code before the form is submitted.

form.taxi is prepared for transmission via XHR requests. In order for your transmissions to be recognized as such, it is mandatory that the Accept header with the value application/json is sent along with the request.

Example of an XHR request

<form action="https://form.taxi/s/FORM_CODE" id="my-form" method="POST">
    Name: <input type="text" name="Name"><br>
    Email: <input type="email" name="Email"><br>
    Nachricht: <textarea name="Message"></textarea><br>
    <input type="submit" value="Send">
</form>
<script type="text/javascript">

  var form = document.getElementById("my-form");
  form.onsubmit = function(event) {
    event.preventDefault();

    var formData = new FormData(form);
    var xhr = new XMLHttpRequest();
    xhr.open("POST", form.action, true);
    xhr.setRequestHeader('Accept', 'application/json');
    xhr.onload = function(e) {

      // Response
      try {
        var response = JSON.parse(xhr.response);
      } catch(e) {
        var response = { success: false, error_msg: 'no json request' }
      }

      // Success
      if(xhr.status === 200 && response.success == true) {

        // Redirect to Success-URL
        // ... or display Success-Message
        alert("Success!");
      }

      // Error
      else {

        // Display Error Message
        var msg = response.error;
        if(response.error_msg != '')
          msg = response.error_msg;
        alert("Error: " + msg);
      }
    };

    xhr.send(formData);
  };

</script>