Explain Codes LogoExplain Codes Logo

Send POST data using XMLHttpRequest

javascript
xmlhttprequest
post-requests
javascript-requests
Nikita BarsukovbyNikita Barsukov·Sep 11, 2024
TLDR
var xhr = new XMLHttpRequest(); xhr.open("POST", 'your-endpoint-url'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify({ param1: 'value1', param2: 'value2' }));

Using an XMLHttpRequest to POST data? Serialize your payload with JSON.stringify(). Make sure to set Content-Type to 'application/json' for proper server handling.

Breaking down the code

Defining your request headers

In POST requests, letting the server know what kind of data you're sending is essential. We're using the 'application/json' MIME type here, but it can be changed to 'application/x-www-form-urlencoded' if you're sending form data instead.

URL encoding and payload preparation

Before our data can embark on its journey, we first need to package it up. This process, known as encoding, is fundamental for most POST requests.

function convertParams(params) { return Object.keys(params) .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(params[key])) .join('&'); } // Watch your data turn into alphabet soup.

Listening to state changes

Keep an eye on your request's progress with onreadystatechange. Check for completion with readyState == 4, then handle the response based on this.status.

xhr.onreadystatechange = function() { if (this.readyState == 4) { // Ready for the grand reveal? if (this.status == 200) { // Great job, you did it! } else { // Uh-oh. Your program had a little oopsie. } } };

Convenience of FormData

FormData is an object that simplifies data serialization, especially when making POST requests using forms. It can append key-value pairs similar to how you'd fill out a form.

var formData = new FormData(); formData.append('param1', 'value1'); formData.append('param2', 'value2'); // Congratulations, you've just signed up for spam emails! xhr.send(formData);

Don't forget error handling

Every epic saga has a hero and a villain. Every XMLHttpRequest has a success and an error handler.

xhr.onload = function() { // Victory! console.log(this.responseText); }; xhr.onerror = function() { // A wild error appears! console.error("Internet elves not cooperating!"); };

Asynchronicity of XMLHttpRequest

Patience is key. By default, XMLHttpRequest won't wait for a request to finish before moving onto the next line of code.

Advanced application

To better grasp your newfound power of POST requests with XMLHttpRequest, let's dive deeper into practical usages.

Working it with JSON

When dealing with an API that expects JSON, stringifying your payload is an essential step.

xhr.send(JSON.stringify({ user: 'JohnDoe', password: '12345' }));

More than just sending data

As with all great powers, XMLHttpRequest comes with some extra goodies.

xhr.upload.onprogress = function(event) { console.log(`Uploaded ${event.loaded} of ${event.total} bytes`); // Feeling like a hacker yet? }; xhr.abort(); // Sometimes, you just have to let go...

A word on security

A "secure connection" is a lot more than just a green padlock on your address bar. Always consider security in your requests — avoid exposing sensitive data and consider using security tokens or OAuth.