10 Examples of JavaScript POST Requests

Hey there, fellow coder! If you’re on a quest to learn about making POST requests in JavaScript, buckle up because I’ve got you covered. In this post, we will dive deep into the world of POST requests using JavaScript, and I’ll even throw in 10 concrete example scenarios where you’ll find it useful.

But before we dive into those shiny examples, let’s get the basics out of the way first. We’ll talk about how you can send form data using a POST request, what a POST request actually is, and how all of this works in JavaScript. Plus, if you’re feeling stuck and hitting up “Stack Overflow” for help on this topic—I’ve been there—this post might just save you the trouble.

Let’s jump right in!

What is a POST Request?

Okay, so what’s the deal with a POST request? Why not just GET stuff?

A POST request, as the name suggests, is used to send data to a web server to store or update it. Unlike a GET request, which is used simply to retrieve data from a source, POST is all about giving information. This could be anything from submitting forms, uploading files, or even sending JSON data.

In simple terms:

  • POST: Give the server some data (like a form submission or file).
  • GET: Ask the server to give you some data (like downloading a file or data from an API).

Why use POST? You typically use POST when you want your changes to persist on the server. For example, if you submit a form, you’re sending data to the server, which it will then store or use in some way. POST requests are often more secure than GET requests for this reason, as the data is sent in the request body rather than being logged in the URL.

Alright, now that the theory is out of the way, let’s get into the actual JavaScript POST request examples.

How to Trigger a POST in JavaScript?

There are multiple ways to make POST requests in JavaScript, and I’m going to walk through a few. There are modern and more traditional ways, so depending on your project or codebase, you might use one over the other.

Let’s start with XHR (XMLHttpRequest), one of the older or more “classic” ways, then I’ll move on to the cleaner, more modern Fetch API and eventually cover Axios, a popular third-party library. I promise you’ll have 10 solid examples by the time you’re done here!

1. Using XMLHttpRequest

The XMLHttpRequest API (often referred to as simply XHR) is the grandfather of making HTTP requests in JavaScript. It might not be as clean as the Fetch API, but it works pretty much everywhere.

“`javascript
const xhr = new XMLHttpRequest();
xhr.open(“POST”, “https://example.com/api/data”, true);

xhr.setRequestHeader(“Content-Type”, “application/json;charset=UTF-8”);
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(“Data was successfully sent!”, xhr.responseText);
}
};

const postData = JSON.stringify({ name: “John”, age: 30 });
xhr.send(postData);
“`

2. Using Fetch API (Modern Approach)

If you’re working on a modern browser, the fetch() API is my favorite way to handle HTTP requests. It’s sleek, concise, and provides Promises, which means cleaner asynchronous code without getting caught in callback hell.

javascript
fetch(“https://example.com/api/data”, {
method: “POST”,
headers: {
“Content-Type”: “application/json”
},
body: JSON.stringify({ name: “John”, age: 30 })
})
.then(response => response.json())
.then(data => console.log(“Success:”, data))
.catch((error) => {
console.error(“Error:”, error);
});

One of the great things about fetch() is how naturally it works with async/await, which I’ll show later in this guide.

3. Posting JSON Data

If you’re working with APIs these days, you’ll usually be sending JSON data. In this example, we’re sending a simple JSON payload.

“`javascript
const postData = {
name: “Jane”,
age: 25
};

fetch(“https://api.example.com/submit”, {
method: “POST”,
headers: {
“Content-Type”: “application/json”,
},
body: JSON.stringify(postData),
})
.then((response) => response.json())
.then((data) => console.log(“Posted data successfully”, data))
.catch((error) => console.error(“Failed to post data”, error));
“`

4. Sending Form Data with Fetch API

Sometimes, you don’t send JSON; you’re submitting a form instead. Let’s say you’re collecting a user’s data from a form input and want to send it in a POST request.

“`html




“`

Some JavaScript to handle this:

“`javascript
const form = document.getElementById(“myForm”);

form.onsubmit = async function (event) {
event.preventDefault();

const formData = new FormData(form);

try {
    const response = await fetch("https://api.example.com/data", {
        method: "POST",
        body: formData,
    });

    if (response.ok) {
        const result = await response.json();
        console.log("Form posted successfully", result);
    } else {
        console.error("Failed to post form");
    }
} catch (error) {
    console.error("An error occurred", error);
}

};
“`

In this case, we’re not setting the Content-Type; the browser automatically handles that when using FormData.

5. Using Async/Await with Fetch

Let’s say you don’t like .then() chains (heck, who does?). JavaScript provides a much cleaner way to handle promises using async/await, and you can totally do this with your POST request too!

“`javascript
const postData = async () => {
try {
const response = await fetch(“https://example.com/api”, {
method: “POST”,
headers: {
“Content-Type”: “application/json”
},
body: JSON.stringify({ username: “user123”, password: “abc123” })
});

if (!response.ok) {
        throw new Error("Error in POST request");
    }

    const data = await response.json();
    console.log("Posted successfully", data);
} catch (error) {
    console.error("Caught this error:", error);
}

};

postData();
“`

I personally love using async/await because it just makes everything read so nicely, like synchronous code.

6. Posting Files Using Fetch

Want to upload a file? Sure! You can send files as well using fetch().

“`javascript
const fileInput = document.querySelector(‘input[type=”file”]’);
const url = “https://example.com/upload”;

fileInput.addEventListener(‘change’, async () => {
const formData = new FormData();
formData.append(“file”, fileInput.files[0]);

try {
    const response = await fetch(url, {
        method: "POST",
        body: formData
    });

    const result = await response.json();
    console.log("File uploaded successfully", result);
} catch (error) {
    console.error("Error in file upload", error);
}

});
“`

In this case, we’re using FormData to attach the file. Notice that the Content-Type header isn’t necessary; the browser takes care of that.

7. Using Axios for POST Requests

If you haven’t heard of Axios, this is a popular library that simplifies HTTP requests and provides a few goodies like automatic JSON handling, timeout support, etc. Let’s look at an example.

“`javascript
// First, include Axios (you can install it via npm or grab it from a CDN)

axios.post(“https://example.com/api”, {
username: “user1”,
password: “pw123”
})
.then(response => {
console.log(“Data posted with Axios!”, response.data);
})
.catch(error => {
console.error(“Axios POST error”, error);
});
“`

Axios is fantastic when you’re working with many APIs or need more refined control over your requests—definitely give it a try!

8. Posting URL-Encoded Data

While JSON and multipart (form-data) submissions are common, you may run into APIs expecting traditional URL-encoded data. Here’s how you would send URL-encoded data with Fetch:

“`javascript
const urlEncodedData = new URLSearchParams();
urlEncodedData.append(“username”, “user1”);
urlEncodedData.append(“password”, “securePassword123”);

fetch(“https://example.com/api/submit”, {
method: “POST”,
headers: {
“Content-Type”: “application/x-www-form-urlencoded”,
},
body: urlEncodedData.toString(),
})
.then(response => response.json())
.then(data => console.log(“Data Sent!”, data))
.catch(error => console.error(“Error in sending”, error));
“`

9. Posting Data to an Express Server

Chances are you’ll end up working with a backend like Node.js and Express. Here’s how you can handle the POST request on the server side using Express:

“`javascript
const express = require(“express”);
const app = express();
app.use(express.json());

app.post(“/submit”, (req, res) => {
const { name, age } = req.body;
res.json({ message: Data received: ${name} is ${age} years old. });
});

app.listen(3000, () => console.log(“Server running on http://localhost:3000”));
“`

In this Express example, we expect data in the body as JSON and send a response as JSON as well.

10. Sending Axios POST in Async/Await Style

Why not use Axios with async/await too and bring all the goodness together? Here’s how you can do that:

“`javascript
const postData = async () => {
try {
const response = await axios.post(“https://example.com/api/submit”, {
email: “[email protected]”,
password: “newPassword”
});

console.log("Posted successfully", response.data);
} catch (error) {
    console.error("Error posting data", error);
}

};

postData();
“`

JavaScript POST Form Data Example

Now, if you’re working specifically with HTML forms, the most practical example for triggering a POST request is via a form submission. Here’s a complete HTML + JavaScript example where we’ll POST form data to a server:

“`html




const data = await response.json(); console.log("Form data successfully posted", data); } catch (error) { console.error("Posting form data failed", error); } });

“`

This will send every field and the values associated with them, which makes FormData super convenient.

10 Examples of JavaScript POST Requests (Stack Overflow Inspired)

If you’ve spent any time on Stack Overflow (who hasn’t?), you’re familiar with the common requests made by developers around JavaScript and HTTP operations. Most of these examples above came from questions that keep coming up again and again: “How do I send JSON?”, “How can I upload a file?”, and “How do I handle form data?”

If you ever find yourself asking any of these questions, just remember this post—chances are, the code snippets here will do exactly what you need.

Conclusion

JavaScript POST requests are essential for modern web applications, from submitting forms to interacting with APIs. We walked through 10 practical examples covering everything from simple JSON payloads to uploading files or submitting forms.

You now have a versatile toolkit for handling any POST request scenario with JavaScript. Whether you’re using XMLHttpRequest, diving into the cool and modern Fetch API, or want something simpler with Axios, you’re all set to start posting like a pro!

Got questions or cool POST requests of your own to share? Drop them in the comments, and good luck with your coding journey!