Refactor form submission handling for sign up

- Disable submit button and display spinner during form submission to
prevent multiple clicks
- Obtain form field values and send signup request as form data for
processing on the server
This commit is contained in:
James Musselman 2023-11-29 17:58:43 -06:00
parent d2ed1a6007
commit 7682d9fd47

View file

@ -9,6 +9,12 @@ document.addEventListener("DOMContentLoaded", function () {
submitBtn.disabled = !formIsValid; submitBtn.disabled = !formIsValid;
}); });
signupForm.addEventListener("submit", function (event) {
event.preventDefault(); // Prevent the form from being submitted normally
submitSignup();
});
loginForm.addEventListener("submit", function (event) { loginForm.addEventListener("submit", function (event) {
event.preventDefault(); // Prevent the form from being submitted normally event.preventDefault(); // Prevent the form from being submitted normally
submitLogin(); submitLogin();
@ -60,23 +66,61 @@ function checkUsernameAvailability() {
} }
}; };
xhr.send(); xhr.send();
// Disable the button to prevent multiple clicks }
submitBtn.disabled = true;
// Show the spinner
const spinner = document.createElement('i'); function submitSignup() {
spinner.classList.add('fas', 'fa-spinner', 'fa-spin'); // Disable the button to prevent multiple clicks
submitBtn.innerHTML = ''; submitBtn.disabled = true;
submitBtn.appendChild(spinner);
// Show the spinner
// Enable the button and remove the spinner after 5 seconds const spinner = document.createElement('i');
setTimeout(function () { spinner.classList.add('fas', 'fa-spinner', 'fa-spin');
submitBtn.innerHTML = '';
submitBtn.appendChild(spinner);
// Enable the button and remove the spinner after 5 seconds
setTimeout(function () {
submitBtn.disabled = false; submitBtn.disabled = false;
submitBtn.innerHTML = 'Sign Up'; submitBtn.innerHTML = 'Sign Up';
}, 5000); }, 5000);
sleep(5000).then(() => { submitBtn.disabled = false; }); sleep(5000).then(() => { submitBtn.disabled = false; });
// Get the values of the signup form fields
const name = document.getElementById("name").value;
const email = document.getElementById("email").value;
const username = document.getElementById("signup-username").value;
const password = document.getElementById("signup-password").value;
// Create a new FormData object and append the values
const formData = new FormData();
formData.append("name", name);
formData.append("email", email);
formData.append("username", username);
formData.append("password", password);
// Send the signup request as form data
fetch("/signup", {
method: "POST",
body: formData
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error("Signup request failed");
}
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
} }
function sleep(ms) { function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms)); return new Promise(resolve => setTimeout(resolve, ms));
} }