lilachat-frontend/register.js

63 lines
1.6 KiB
JavaScript
Raw Normal View History

2021-07-22 14:01:28 +00:00
//DECLARING VARIABLES AND GRABBING VALUES FROM FORM.
let uname = document.querySelector('#uname').value;
let pin = document.querySelector('#pin').value;
2021-07-17 22:50:58 +00:00
let selected = document.querySelector('#selected').value;
let custom = document.querySelector('#custom').value;
let pronouns = ''
let responseText;
2021-07-22 14:01:28 +00:00
const form = document.querySelector('form');
2021-07-17 22:50:58 +00:00
2021-07-22 14:01:28 +00:00
//SUBMIT FUNCTION &CHECKING IF USERNAME IS TAKEN
2021-07-17 22:50:58 +00:00
2021-07-22 14:01:28 +00:00
form.addEventListener("submit", async function (event) {
event.preventDefault();
const formData = new FormData(form);
2021-07-17 22:50:58 +00:00
2021-07-22 14:01:28 +00:00
uname = formData.get('uname');
pin = formData.get('pin');
selected = formData.get('selected');
custom = formData.get('custom')
if (custom !== '') {
pronouns = custom
} else {
pronouns = selected
}
try {
2021-07-23 06:51:26 +00:00
const isNotTaken = await getUname();
2021-07-17 22:50:58 +00:00
2021-07-23 06:51:26 +00:00
if (isNotTaken.status === "fail") {
2021-07-22 15:10:35 +00:00
register()
2021-07-17 22:50:58 +00:00
} else {
2021-07-22 15:10:35 +00:00
document.querySelector("#errormessage").innerHTML = `${uname} is already taken.`
2021-07-17 22:50:58 +00:00
}
2021-07-22 14:01:28 +00:00
} catch {
document.querySelector("#errormessage").innerHTML = 'An Error has Occurred. Try again later.'
}
2021-07-17 22:50:58 +00:00
})
2021-07-22 14:01:28 +00:00
//FETCH FUNCTIONS. GETTING USERNAME FROM API & REGISTERING USER ASSIGNED NAME AND PIN.
2021-07-17 22:50:58 +00:00
async function getUname() {
let response = await fetch(`/api/users/${uname}`);
responseJson = await response.json();
return responseJson;
2021-07-17 22:50:58 +00:00
}
async function register() {
2021-07-23 06:51:26 +00:00
let sendRegisterInfo = { "name": uname, "pin": pin, "pronouns": pronouns }
fetch('/api/register/', {
2021-07-17 22:50:58 +00:00
method: 'POST',
headers: {
2021-07-23 06:51:26 +00:00
'Content-Type': 'application/json',
},
body: JSON.stringify(sendRegisterInfo),
2021-07-22 14:01:28 +00:00
});
document.querySelector("#errormessage").innerHTML = 'Registered!'
2021-07-22 15:10:35 +00:00
window.location.replace("/login.html")
2021-07-17 22:50:58 +00:00
}