In my previous article, we looked at how to make an HTTP POST request using XMLHttpRequest (XHR) in vanilla JavaScript. Since the most common use of XHR is for sending an asynchronous request with JSON payload, it's good to know how to do it.

JSON stands for JavaScript Object Notation and is a popular format for sharing data with the server and displaying the result to the client.

The following example shows how you can use the XHR to make a JSON POST request in JavaScript:

const xhr = new XMLHttpRequest()

// listen for `load` event
xhr.onload = () => {
  // print JSON response
  if (xhr.status >= 200 && xhr.status < 300) {
    // parse JSON
    const response = JSON.parse(xhr.responseText)
    console.log(response)
  }
}

// create a JSON object
const json = {
  email: 'eve.holt@reqres.in',
  password: 'cityslicka'
}

// open request
xhr.open('POST', 'https://reqres.in/api/login')

// set `Content-Type` header
xhr.setRequestHeader('Content-Type', 'application/json')

// send rquest with JSON payload
xhr.send(JSON.stringify(json))

Take a look at the making HTTP requests using XHR tutorial to learn about all available options.

Send JSON request using Fetch API

If you work with modern browsers only, I'd suggest using the Fetch API instead of XHR. It has clear and concise syntax and also supports promises:

// create a JSON object
const json = {
  email: 'hi@attacomsian.com',
  password: '123abc'
}

// request options
const options = {
  method: 'POST',
  body: JSON.stringify(json),
  headers: {
    'Content-Type': 'application/json'
  }
}

// send post request
fetch('/login', options)
  .then(res => res.json())
  .then(res => console.log(res))
  .catch(err => console.error(err))

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