How to Create a New Post Using JavaScript and the Fetch API

How to Create a New Post Using JavaScript and the Fetch API

How to Create a New Post Using JavaScript and the Fetch API

Sending data to a server is a crucial aspect of modern web applications. Whether you're submitting a form, saving user preferences, or creating a new resource, the fetch API provides a straightforward way to send data via a POST request.

In this blog post, we’ll build a webpage where users can create a new post by entering details in a form. The data is sent to a server using the fetch API, and the server's response is displayed dynamically.

https://basescripts.com/how-to-create-a-new-post-using-javascript-and-the-fetch-api


The Complete Code Example

Below is the full HTML code for creating a new post:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Create Post Example</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 20px;
    }
    #result {
      margin-top: 20px;
      white-space: pre-wrap;
      background-color: #f4f4f4;
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 5px;
    }
    #error {
      margin-top: 20px;
      color: red;
      font-weight: bold;
    }
  </style>
</head>
<body>
  <h1>Create a New Post</h1>
  <form id="postForm">
    <label for="title">Title:</label>
    <input type="text" id="title" name="title" required /><br /><br />

    <label for="body">Body:</label><br />
    <textarea id="body" name="body" rows="4" required></textarea><br /><br />

    <label for="userId">User ID:</label>
    <input type="number" id="userId" name="userId" required /><br /><br />

    <button type="submit">Create Post</button>
  </form>

  <div id="result"></div>
  <div id="error"></div>

  <script>
    document.getElementById('postForm').addEventListener('submit', event => {
      event.preventDefault();

      const title = document.getElementById('title').value;
      const body = document.getElementById('body').value;
      const userId = document.getElementById('userId').value;

      const resultDiv = document.getElementById('result');
      const errorDiv = document.getElementById('error');

      // Clear previous results and errors
      resultDiv.textContent = '';
      errorDiv.textContent = '';

      fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          title: title,
          body: body,
          userId: parseInt(userId, 10),
        }),
      })
        .then(response => {
          if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
          }
          return response.json();
        })
        .then(createdPost => {
          resultDiv.textContent = `Post created successfully:\\n${JSON.stringify(createdPost, null, 2)}`;
        })
        .catch(error => {
          errorDiv.textContent = `Error creating post: ${error.message}`;
        });
    });
  </script>
</body>
</html>
        

Code Breakdown

1. HTML Form

The form includes fields for the post title, body, and user ID. A submit button triggers the JavaScript function to send the data.

<form id="postForm">
  <label for="title">Title:</label>
  <input type="text" id="title" required /><br /><br />
  <label for="body">Body:</label><br />
  <textarea id="body" rows="4" required></textarea><br /><br />
  <label for="userId">User ID:</label>
  <input type="number" id="userId" required /><br /><br />
  <button type="submit">Create Post</button>
</form>
        

2. JavaScript Logic

The fetch API sends a POST request with the data entered in the form:

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    title: title,
    body: body,
    userId: parseInt(userId, 10),
  }),
})
        

If the request is successful, the server's response is displayed in the #result container. Errors are caught and displayed in the #error container.

3. Styling

Minimal CSS is used to style the results and error messages:

#result {
  background-color: #f4f4f4;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
#error {
  color: red;
  font-weight: bold;
}
        

How It Works

  1. Form Submission: The form captures user input for the post title, body, and user ID.
  2. Send Data to Server: When the form is submitted, the fetch API sends a POST request to https://jsonplaceholder.typicode.com/posts, simulating the creation of a new post.
  3. Display Response: The server responds with a JSON object, which includes the newly created post's details. This response is displayed in a formatted JSON structure on the webpage.
  4. Error Handling: If the server returns an error or the fetch operation fails, an error message is displayed.


Running the Code

  1. Save the file as index.html and open it in a browser.
  2. Fill in the form fields and click "Create Post."
  3. Observe the server's response displayed on the page.


Why This Example is Useful

  • Hands-On API Interaction: Learn how to send data to a server using the fetch API.
  • Practical Form Handling: See how to capture and validate user input in a real-world scenario.
  • Error Handling: Understand how to handle errors gracefully and improve the user experience.


Next Steps

To expand on this example:

  • Add form validation to check for empty fields before sending the request.
  • Include a loading spinner to indicate that the request is in progress.
  • Connect to a real API to handle actual data instead of using a placeholder API.

By following this tutorial, you’ve gained the knowledge to send data to a server using JavaScript and dynamically display the results on your webpage. This skill is fundamental for building interactive web applications.

To view or add a comment, sign in

More articles by JavaScript Developer WorldWide

Insights from the community

Others also viewed

Explore topics