Building a Simple Web Form to Create Posts Using the Fetch API

Forms are an essential part of any web application, enabling users to input and submit data. In this blog post, we’ll walk through creating a simple HTML form that captures user input and submits it to a server using the fetch API. The example leverages https://jsonplaceholder.typicode.com/posts as a test API endpoint for demonstration.


Features of the Application

  • A styled HTML form with fields for post title and content.
  • Validation to ensure required fields are filled.
  • Submission of form data as JSON using the fetch API.
  • Feedback messages displayed to users for success or error scenarios.

Full Code Implementation

HTML and CSS for the Form

The form includes fields for a post title and content, styled with CSS for a clean and user-friendly interface.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create New Post</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
form {
max-width: 400px;
margin: auto;
border: 1px solid #ccc;
padding: 20px;
border-radius: 5px;
background-color: #f9f9f9;
}
label {
display: block;
margin-bottom: 8px;
font-weight: bold;
}
input, textarea {
width: 100%;
padding: 8px;
margin-bottom: 15px;
border: 1px solid #ddd;
border-radius: 4px;
}
button {
padding: 10px 20px;
background-color: #28a745;
border: none;
color: white;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #218838;
}
.message {
text-align: center;
margin-top: 20px;
font-size: 1.1rem;
}
</style>
</head>
<body>
<h1>Create a New Post</h1>
<form id="postForm">
<label for="title">Post Title:</label>
<input type="text" id="title" name="title" required />

<label for="body">Post Content:</label>
<textarea id="body" name="body" rows="5" required></textarea>

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

<div class="message" id="formMessage"></div>

<!-- Include the JavaScript file -->
<script src="form.js"></script>
</body>
</html>

JavaScript for Form Submission

The JavaScript code listens for form submissions, validates the fields, and sends the data to the API endpoint. It provides feedback based on the response.

document.addEventListener('DOMContentLoaded', () => {
const postForm = document.getElementById('postForm');
const formMessage = document.getElementById('formMessage');

// Listen for form submission
postForm.addEventListener('submit', (event) => {
event.preventDefault(); // Prevent default form submission behavior

// Capture form data
const title = document.getElementById('title').value.trim();
const body = document.getElementById('body').value.trim();

// Clear any existing messages
formMessage.textContent = '';

// Validate form fields (basic validation)
if (!title || !body) {
formMessage.textContent = 'Please fill in both fields.';
formMessage.style.color = 'red';
return;
}

// Prepare data to send (as a JSON object)
const postData = {
title: title,
body: body,
userId: 1 // Hard-coded user ID for demonstration
};

// Send POST request to the test API endpoint
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
})
.then(response => {
if (!response.ok) {
throw new Error(`Server responded with status: ${response.status}`);
}
return response.json();
})
.then(data => {
// Display success message
formMessage.textContent = `Post created successfully with ID ${data.id}!`;
formMessage.style.color = 'green';

// Optionally, reset the form
postForm.reset();
})
.catch(error => {
// Display error message
formMessage.textContent = `Error submitting post: ${error.message}`;
formMessage.style.color = 'red';
});
});
});

How It Works

1. HTML Form

  • The form includes fields for a title and body, and a “Submit Post” button.
  • The form is styled to provide a clean and intuitive user experience.

2. Form Submission

  • The JavaScript intercepts the form’s submission to prevent the default behavior.
  • It captures the user input and performs basic validation to ensure all required fields are filled.

3. Data Submission

  • The form data is converted into a JSON object.
  • A fetch request with the POST method sends the JSON data to the server.

4. Response Handling

  • On a successful response, the server returns the created post’s details, including a new id. A success message is displayed to the user.
  • If the request fails (e.g., due to a network error or server issue), an error message is shown.

Try It Out

  1. Copy the HTML code into a file named index.html.
  2. Copy the JavaScript code into a file named form.js in the same directory.
  3. Open index.html in your browser.
  4. Fill in the form and click “Submit Post.”

Enhancements You Can Add

  • Client-Side Validation:
    Add more detailed validation to check input lengths or patterns.
  • Loading Spinner:
    Display a loading indicator while the form is being submitted.
  • Dynamic User IDs:
    Allow users to specify a custom user ID instead of using a hardcoded value.

This simple application demonstrates how to build a form that interacts with a server using the fetch API. It’s a practical example of modern JavaScript techniques, and with a little enhancement, you can use it as a foundation for more complex projects.