Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to Use the JavaScript Fetch API to Post Data

In this blog, we are going to discuss how to use the JavaScript Fetch API to post data to a server. This tutorial is written for someone who is learning programming and assumes no prior knowledge of JavaScript or Fetch API. We will try our best to avoid jargon, and if any jargon is used, we will make sure to explain it.

What is Fetch API?

Fetch API is a modern, powerful, and flexible way to make HTTP requests in JavaScript. It is built into web browsers, which means you don't need any external libraries to use it. Fetch API can be used to send data (post) and receive data (get) from servers, making it an essential tool for working with APIs (Application Programming Interfaces) and creating dynamic web applications.

What is POST request?

In the context of web development, POST is an HTTP method used to send data from a client (your browser) to a server. When you submit a form on a website, for example, the browser sends a POST request to the server with the data you entered in the form. The server then processes the data and takes appropriate action, like saving it to a database or sending an email.

Prerequisites

Before diving into the Fetch API and POST requests, make sure you have a basic understanding of:

  • HTML: To create a simple form to submit data.
  • JavaScript: To write the code that will handle the form submission and use Fetch API.

Creating a simple HTML form

To demonstrate how to use Fetch API for sending POST requests, let's create a simple HTML form where users can enter their name and email address:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Form</title>
</head>
<body>
    <form id="contact-form">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
        <br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <br>
        <button type="submit">Submit</button>
    </form>

    <script src="main.js"></script>
</body>
</html>

This code creates a simple form with two input fields, one for the name and another for the email. The form has an ID (contact-form) that we'll use in our JavaScript code to interact with it.

Writing the JavaScript code

Now, let's write the JavaScript code that will handle the form submission and use the Fetch API to send a POST request to a server. Create a new file named main.js and add the following code:

document.getElementById("contact-form").addEventListener("submit", (event) => {
    event.preventDefault();

    const name = document.getElementById("name").value;
    const email = document.getElementById("email").value;

    const data = {
        name: name,
        email: email
    };

    postData("https://jsonplaceholder.typicode.com/posts", data)
        .then((response) => {
            console.log(response);
        })
        .catch((error) => {
            console.error("Error:", error);
        });
});

async function postData(url = "", data = {}) {
    const response = await fetch(url, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
    });

    return await response.json();
}

Let's break down this code step by step:

We use document.getElementById to get a reference to our form element and then add an event listener for the "submit" event. This event is triggered when the user clicks the "Submit" button.

Inside the event listener, we use event.preventDefault() to prevent the default behavior of the form submission, which would refresh the page.

We get the values entered by the user in the input fields using document.getElementById("name").value and document.getElementById("email").value.

We create a JavaScript object named data with the properties name and email and their corresponding values.

We call the postData function, passing in the URL of the server we want to send the data to and the data object. In this example, we are using a mock API endpoint https://jsonplaceholder.typicode.com/posts that simulates a real server.

The postData function is an asynchronous function that sends a POST request using the Fetch API. We pass in the url and data as parameters.

Inside the postData function, we use the Fetch API to send a POST request by providing the url, setting the HTTP method to "POST", specifying the "Content-Type" header as "application/json", and converting the data object to a JSON string using JSON.stringify.

Once the POST request is completed, the Fetch API returns a Promise that resolves with the server's response. We use await response.json() to convert the response to a JavaScript object and return it from the postData function.

In the event listener, we use the .then() and .catch() methods to handle the successful response or any errors that might occur during the request.

Now, when you open the HTML file in your browser and submit the form, the JavaScript code will send a POST request to the mock API endpoint with the user's data, and you should see the server's response in the browser console.

Conclusion

In this tutorial, we learned how to use the JavaScript Fetch API to send POST requests and submit data to a server. This is a powerful and flexible way to interact with APIs and create dynamic web applications.

With a basic understanding of Fetch API and POST requests, you can now start exploring more advanced use cases, such as handling file uploads, working with cookies, and implementing authentication.

Remember to keep practicing and experimenting with different APIs and web development projects to further improve your skills. Good luck, and happy coding!