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,6 +66,10 @@ function checkUsernameAvailability() {
} }
}; };
xhr.send(); xhr.send();
}
function submitSignup() {
// Disable the button to prevent multiple clicks // Disable the button to prevent multiple clicks
submitBtn.disabled = true; submitBtn.disabled = true;
@ -75,8 +85,42 @@ function checkUsernameAvailability() {
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));
} }