ARTICLE AD BOX
When you submit the form, the onsubmit function runs. It starts an asynchronous fetch request and then returns undefined. This does not stop the normal behaviour of the form, which submits to MailingList.html. This causes the browser to leave the current page and kill all the JS running on it (before getting as far as resolving the promise returned by fetch and calling alert).
The quick and dirty approach to fixing this would be to return false from the function.
A more modern approach would make use of the browser's built-in validation system, break the function up into smaller functions, and attach the handler with addEventListener.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Stay Informed — Join Our Mailing List</title> <style> h1, label, button { text-transform: uppercase; /* Using CSS instead of raw ALL CAPS stops screen readers treating it as an abbreviation to be read out letter by letter */ } </style> </head> <body> <div id="FormHome"> <h1>Stay Informed — Join Our Mailing List</h1> <form> <label for="name">Name:</label><br> <input type="text" id="name" name="name" required><br> <label for="email">Email:</label><br> <input type="email" id="email" name="email" required> <button>Submit</button> </form> </div> <script> const form = document.querySelector('form'); const getFormData = () => { const name = form.querySelector("#name").value.trim() const email = form.querySelector("#email").value; return { email, name }; } const postFormData = (data) => fetch('//example.com', { method: "post", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }); const handleResponse = (response) => { if (response.ok) { alert("Thank you. You are now signed up for our mailing list"); document.location.href = "MailingList.html"; } else if (response.status === 400) { alert("Invalid data was sent to the server") } else { alert("Sorry, something went wrong."); } } const formHandler = async (event) => { event.preventDefault(); if (!form.checkValidity()) { return false; } const data = getFormData(); const response = await postFormData(data); handleResponse(response); } form.addEventListener("submit", formHandler); </script> </body> </html>It would also probably avoid using alert() in favour of an inline message added using DOM methods.
