# How to send JSON request using XMLHttpRequest (XHR)

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Feb 22, 2020, updated Oct 12, 2022. Topics: JSON, JavaScript.
Canonical URL: https://attacomsian.com/blog/xhr-json-post-request

> A short tutorial to learn how to make JSON POST request to the server using XMLHttpRequest (XHR) in JavaScript.

In my previous article, we looked at how to make an HTTP POST request using [XMLHttpRequest (XHR)](https://attacomsian.com/blog/xhr-post-request) in vanilla JavaScript. Since the most common use of XHR is for sending an asynchronous request with [JSON](https://attacomsian.com/blog/what-is-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:

```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](https://attacomsian.com/blog/http-requests-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](https://attacomsian.com/blog/javascript-fetch-api) instead of XHR. It has clear and concise syntax and also supports [promises](https://attacomsian.com/blog/promises-javascript):

```javascript
// 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))
```
