XMLHttpRequest (XHR) is a built-in browser object that can be used to make HTTP requests in JavaScript to exchange data between the client and server. It is supported by all modern and old browsers.

In this article, you'll learn how to make an HTTP POST request using XHR. Let us say we have the following HTML form:

<form id="signup-form" action="/signup" method="POST">
    <input type="text" name="name" placeholder="Enter name">
    <input type="email" name="email" placeholder="Enter Email">
    <input type="password" name="password" placeholder="Enter Password">
    <button type="submit" role="button">Submit</button>
</form>

We want to ensure when the user clicks on the "Submit" button, the form is submitted asynchronously through XHR. The first step is to attach an event handler to the <form> to capture the submit event:

const form = document.querySelector('#signup-form')

// listen for submit even
form.addEventListener('submit', () => {
  // TODO: submit post request here
})

The next step is to create and send an actual POST request. If you are already familiar with jQuery, sending a POST request is similar to the $.post() method. Here is what it looks like:

form.addEventListener('submit', event => {
  // disable default action
  event.preventDefault()

  // configure a request
  const xhr = new XMLHttpRequest()
  xhr.open('POST', '/signup')

  // prepare form data
  let data = new FormData(form)

  // set headers
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')

  // send request
  xhr.send(data)

  // listen for `load` event
  xhr.onload = () => {
    console.log(xhr.responseText)
  }
})

That's it. The above code will send an HTTP POST request to the server and print the response on the console.

Send POST request using Fetch API

You can easily simplify the above request using the Fetch API. Fetch is a promise-based alternative to XHR for making HTTP requests. It is much more readable and customizable:

form.addEventListener('submit', event => {
  // disable default action
  event.preventDefault()

  // make post request
  fetch('/signup', {
    method: 'POST',
    body: new FormData(form),
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
    .then(res => res.text())
    .then(html => console.log(html))
    .catch(err => console.error(err))
})

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.