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 quick 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 make sure that when the user clicks on the "Submit" button, the form is submitted asynchronously through XHR. The first step is to attach an event handler 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 quite similar to the $.post() method. Here is how 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.

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 @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, Buy me a coffee (cost $5) .

Need help to launch a new product? I am available for contract work. Hire me to accomplish your business goals with engineering and design.