generate html for newsletter subcriber form with name and email that saves data to a…
- User
generate html for newsletter subcriber form with name and email that saves data to a POST API using fetch.
- Assistant
Sure! Here's an example of an HTML form that collects a user's name and email and saves the data to a POST API using the fetch API.
<!DOCTYPE html> <html> <head> <title>Newsletter Subscription</title> </head> <body> <h2>Subscribe to our Newsletter</h2> <form id="subscriptionForm"> <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">Subscribe</button> </form> <script> const form = document.getElementById('subscriptionForm'); form.addEventListener('submit', function(event) { event.preventDefault(); // Prevent form submission const name = document.getElementById('name').value; const email = document.getElementById('email').value; const data = { name: name, email: email }; fetch('your-api-endpoint', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => response.json()) .then(result => { console.log('Subscription successful!', result); }) .catch(error => { console.error('Error:', error); }); }); </script> </body> </html> - User
generate html page for newsletter subcription with name and email that saves data to a POST API using fetch.
- Assistant
Certainly! Here's an example of an HTML page that contains a newsletter subscription form with fields for name and email. When the user submits the form, the data is sent to a POST API endpoint using the fetch API.
<!DOCTYPE html> <html> <head> <title>Newsletter Subscription</title> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <h1>Subscribe to Our Newsletter</h1> <form id="subscriptionForm"> <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">Subscribe</button> </form> <script> const form = document.getElementById('subscriptionForm'); form.addEventListener('submit', function(event) { event.preventDefault(); // Prevent form submission const name = document.getElementById('name').value; const email = document.getElementById('email').value; const data = { name: name, email: email }; axios.post('your-api-endpoint', data) .then(response => { console.log('Subscription successful', response.data); }) .catch(error => { console.error('Error:', error); }); form.reset(); // Clear form fields after submission }); </script> </body> </html>