How to send POST request using XMLHttpRequest (XHR)

In this article 👇

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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.