How to Make POST Requests with XMLHttpRequest

Learn how to send data to a server using JavaScript’s XMLHttpRequest.

Max N
2 min readApr 12, 2024

When you want to send data to a server, POST requests are often the best choice. In this article, we’ll explore how to use the XMLHttpRequest object in JavaScript to make POST requests.

Why Use POST Requests?

  • Sending data: POST requests are great for sending data to a server, such as form submissions.
  • Security: Sensitive data (like passwords) is not visible in the URL.
  • Custom data: POST requests allow sending different types of data (like JSON or form data).

Making a POST Request with XMLHttpRequest

Here’s how you can make a POST request using XMLHttpRequest:

const xhr = new XMLHttpRequest();
const url = 'https://api.example.com/submit-data';
const data = JSON.stringify({
name: 'John Doe',
email: 'johndoe@example.com',
});

xhr.open('POST', url, true);

// Set request header for JSON data
xhr.setRequestHeader('Content-Type', 'application/json');

xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log('Response received:', xhr.responseText);
} else {…

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet