Sure! Below is an example of an HTML form that collects name and email for newsletter subscription. It uses the Fetch API to send a POST request with the name and email as body parameters to a specific endpoint.
<!DOCTYPE html>
<html>
<head>
<title>Newsletter Subscription</title>
<script>
function subscribeNewsletter() {
const form = document.getElementById('subscribeForm');
const name = form.name.value;
const email = form.email.value;
// Validate name and email fields
if (name === '' || email === '') {
alert('Please enter both name and email.');
return;
}
// Create the request body
const body = {
name: name,
email: email
};
// Send a POST request using Fetch API
fetch('https://example.com/subscribe', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
})
.then(response => {
if (response.ok) {
alert('Successfully subscribed to the newsletter!');
// Clear the form fields after successful subscription
form.name.value = '';
form.email.value = '';
} else {
alert('Failed to subscribe. Please try again later.');
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred. Please try again later.');
});
}
</script>
</head>
<body>
<h2>Subscribe to our Newsletter</h2>
<form id="subscribeForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<input type="button" value="Subscribe" onclick="subscribeNewsletter()">
</form>
</body>
</html>
In the above code snippet, replace 'https://example.com/subscribe' with the actual URL where you want to send the subscription details.
When the user clicks the "Subscribe" button, the subscribeNewsletter function is called. It first validates the name and email fields to ensure they are not empty. Then, it creates a request body object with the name and email values. Finally, it sends a POST request using the Fetch API, including the body as a JSON string. The server should handle the request and respond accordingly. If the POST request is successful (status code 200), an alert is displayed indicating successful subscription. Otherwise, an appropriate error message is displayed.