fix: display error message to user if form submission fails

This commit is contained in:
Ryan Mwangi 2024-11-18 19:11:03 +03:00
parent 982514c727
commit c7d8799da1
3 changed files with 36 additions and 4 deletions

View File

@ -57,13 +57,14 @@
<div class="container">
<h2>Get Started</h2>
<p>Ready to take the next step in your IT career? Apply today!</p>
<form id="applicationForm" method="post" action="https://mailer.melonion.me/subscription/form">
<form id="applicationForm">
<input type="hidden" name="list_id" value="3">
<input type="text" name="name" placeholder="Your Name" required>
<input type="email" name="email" placeholder="Your Email" required>
<textarea name="message" placeholder="Why are you interested in this program?" required></textarea>
<button type="submit" class="cta-button">Submit Application</button>
</form>
<div id="responseMessage"></div>
</div>
</section>

View File

@ -5,6 +5,11 @@ document.getElementById('applicationForm').addEventListener('submit', function(e
const formData = new FormData(this);
const data = Object.fromEntries(formData.entries());
// Clear previous messages
const responseMessage = document.getElementById('responseMessage');
responseMessage.textContent = '';
responseMessage.className = '';
// Send form data to server-side endpoint
fetch('/submit', {
method: 'POST',
@ -13,12 +18,23 @@ document.getElementById('applicationForm').addEventListener('submit', function(e
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(response => {
if (!response.ok) {
// If the response status is not OK, throw an error
return response.json().then(err => {
throw new Error(err.message || 'An error occurred');
});
}
return response.json();
})
.then(result => {
console.log('Success:', result);
document.body.innerHTML = '<h2>Thank you for your application!</h2>';
responseMessage.textContent = 'Thank you for your application!';
responseMessage.className = 'success';
})
.catch(error => {
console.error('Error:', error);
responseMessage.textContent = `Error: ${error.message}`;
responseMessage.className = 'error';
});
});

View File

@ -149,4 +149,19 @@ footer {
footer p {
font-size: 0.9rem;
}
}
/*response messages*/
#responseMessage {
margin-top: 1em;
font-weight: bold;
}
#responseMessage.success {
color: green;
}
#responseMessage.error {
color: red;
}