Explain Codes LogoExplain Codes Logo

Pure JavaScript Send POST Data Without a Form

javascript
async-programming
browser-compatibility
debugging
Nikita BarsukovbyNikita Barsukov·Mar 3, 2025
TLDR

Hitting the ground running with fetch:

fetch('your-endpoint', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({key: 'value'}) // Your key-value pairs }) .then(res => res.json()) .then(data => console.log('Success:', data)) .catch(error => console.error('Error:', error));

This chunk of code makes a POST request, sends JSON data, and conveniently lets you view either the server's response or any error that decided to crash the party.

Oldie but a Goldie: XMLHttpRequest

When fetch takes a day off or a browser compatibility issue arises, XMLHttpRequest is the seasoned workhorse you can rely on:

const xhr = new XMLHttpRequest(); // No POST-code here! Sorry, had to do it. xhr.open('POST', 'your-endpoint', true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { console.log('Success:', JSON.parse(xhr.responseText)); } }; xhr.send(JSON.stringify({key: 'value'}));

Work with JSON data in POST? Done. Listen for the onreadystatechange event like it's a hit radio song? You've got it!

Advanced techniques and edge cases

Async wizardry

Working with fetch and XMLHttpRequest means stepping into a world of asynchronous actions. Handling callbacks, working with promises, or relying on async/await are crucial techniques, as server's response is a bit of a Slowpoke Rodney, compared to JavaScript's hyperactive execution pace.

Older browsers' blues

Need to cater to Barker's Mill enthusiasts running a browser that was popular when dinosaurs roamed the earth? Check how to initiate an XMLHttpRequest object correctly for a wide range of browsers.

Error-radar mode: Engage!

Watch out for nasty network errors or shifty parsing elves trying to trip up your perfect code! xhr.onerror for XMLHttpRequest and catch for fetch are your doorman and security at this JavaScript party.

Meeting half-way: server-side work

Your server-side system better roll out the red carpet for POST requests, or... what are we even doing here? Ensure your back-end logic is robust and ready for your perfectly crafted JavaScript magic.

Encoding data: Dressing up your data

Sometimes you need to ditch the comfy jeans (JSON) and put your data in a sharp tuxedo, aka application/x-www-form-urlencoded. Here's how:

const formData = new URLSearchParams(); formData.append('key', 'value'); fetch('your-endpoint', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: formData }) .then(response => response.text()) .then(data => console.log('Tuxedo-Encoded Success:', data)) .catch(error => console.error('Tuxedo-Encoded Error:', error));

Don't forget, if your data is wearing a tuxedo, your server better be ready for some black-tie action!

Debugging: The Sherlock Holmes mode

Unleash your inner detective and investigate your JavaScript POST requests with handy browser devtools and console logs. Investigate response clues, unpack payloads, and crack the code of error messages. The game is on!