Submitting a Form with AJAX in JavaScript

Submitting a form without reloading the entire page is a common requirement in modern web development.

AJAX (Asynchronous JavaScript and XML) provides a solution for handling form submissions asynchronously, allowing you to send and receive data from the server in the background.

In this article, we'll explore how to submit a form with AJAX in JavaScript.

Using the FormData Object

To submit a form with AJAX, we can use the FormData object to construct a set of key/value pairs representing form fields and their values.

This makes it easy to handle various types of form data, including text fields, checkboxes, and file inputs.

Here's a step-by-step guide:

// Get a reference to the form element
const myForm = document.getElementById('myForm');

// Add a submit event listener to the form
myForm.addEventListener('submit', function (event) {
  // Prevent the default form submission
  event.preventDefault();

  // Create a FormData object from the form
  const formData = new FormData(myForm);

  // Call the function to submit the form with AJAX
  submitForm(formData);
});

// Function to submit the form with AJAX
function submitForm(formData) {
  // Create an XMLHttpRequest object
  const xhr = new XMLHttpRequest();

  // Configure the XMLHttpRequest
  xhr.open('POST', '/submit', true);

  // Set the onload event handler
  xhr.onload = function () {
    if (xhr.status === 200) {
      // Form submitted successfully
      console.log('Form submitted successfully:', xhr.responseText);
    } else {
      // Error during form submission
      console.error('Error during form submission:', xhr.statusText);
    }
  };

  // Set the onerror event handler
  xhr.onerror = function () {
    console.error('Network error during form submission.');
  };

  // Send the FormData object to the server
  xhr.send(formData);
}

In this code:

Full Example

Let's consider a complete example with an HTML structure containing a form:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Form Submission Example</title>
</head>
<body>

  <form id="myForm">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>

    <button type="submit">Submit</button>
  </form>

  <script>
    // Get a reference to the form element
    const myForm = document.getElementById('myForm');

    // Add a submit event listener to the form
    myForm.addEventListener('submit', function (event) {
      // Prevent the default form submission
      event.preventDefault();

      // Create a FormData object from the form
      const formData = new FormData(myForm);

      // Call the function to submit the form with AJAX
      submitForm(formData);
    });

    // Function to submit the form with AJAX
    function submitForm(formData) {
      // Create an XMLHttpRequest object
      const xhr = new XMLHttpRequest();

      // Configure the XMLHttpRequest
      xhr.open('POST', '/submit', true);

      // Set the onload event handler
      xhr.onload = function () {
        if (xhr.status === 200) {
          // Form submitted successfully
          console.log('Form submitted successfully:', xhr.responseText);
        } else {
          // Error during form submission
          console.error('Error during form submission:', xhr.statusText);
        }
      };

      // Set the onerror event handler
      xhr.onerror = function () {
        console.error('Network error during form submission.');
      };

      // Send the FormData object to the server
      xhr.send(formData);
    }
  </script>
</body>
</html>

In this example:

Conclusion

Submitting a form with AJAX in JavaScript provides a seamless and dynamic way to interact with the server without reloading the entire page.

By leveraging the FormData object and XMLHttpRequest, you can easily handle form submissions asynchronously, improving the user experience and making your web applications more responsive.

Incorporate this technique into your projects to create interactive and modern forms that seamlessly communicate with the server.