From c7d8799da15c92506538d4a6fbeaddfefbe76b81 Mon Sep 17 00:00:00 2001 From: Ryan Mwangi Date: Mon, 18 Nov 2024 19:11:03 +0300 Subject: [PATCH] fix: display error message to user if form submission fails --- public/index.html | 3 ++- public/index.js | 20 ++++++++++++++++++-- public/styles.css | 17 ++++++++++++++++- 3 files changed, 36 insertions(+), 4 deletions(-) diff --git a/public/index.html b/public/index.html index 67f2353..22c0575 100644 --- a/public/index.html +++ b/public/index.html @@ -57,13 +57,14 @@

Get Started

Ready to take the next step in your IT career? Apply today!

-
+
+
diff --git a/public/index.js b/public/index.js index 444aaa9..a66c08d 100644 --- a/public/index.js +++ b/public/index.js @@ -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 = '

Thank you for your application!

'; + responseMessage.textContent = 'Thank you for your application!'; + responseMessage.className = 'success'; }) .catch(error => { console.error('Error:', error); + responseMessage.textContent = `Error: ${error.message}`; + responseMessage.className = 'error'; }); }); diff --git a/public/styles.css b/public/styles.css index 317e2d0..fb2e785 100644 --- a/public/styles.css +++ b/public/styles.css @@ -149,4 +149,19 @@ footer { footer p { font-size: 0.9rem; -} \ No newline at end of file +} + +/*response messages*/ + +#responseMessage { + margin-top: 1em; + font-weight: bold; +} + +#responseMessage.success { + color: green; +} + +#responseMessage.error { + color: red; +}