How to send JSON request using XMLHttpRequest (XHR)

In this article 👇

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.

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.