diff options
author | Lars Krönner | 2020-10-10 18:40:46 +0200 |
---|---|---|
committer | GitHub | 2020-10-10 18:40:46 +0200 |
commit | c2cb67575c8ee623b775d1f5fd28c0a60a9288dc (patch) | |
tree | a9285cef4e2dc3451ed609be2a34bbf21580c35e /profile/public/script.js | |
parent | 16ebbb932c0b780c11d3e574bc24a515eb095f5f (diff) | |
parent | 1f45ede8253421439e07790375b72a31ceef33ed (diff) |
Merge pull request #4 from marvinborner/profile
Profile
Diffstat (limited to 'profile/public/script.js')
-rw-r--r-- | profile/public/script.js | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/profile/public/script.js b/profile/public/script.js new file mode 100644 index 0000000..a386f56 --- /dev/null +++ b/profile/public/script.js @@ -0,0 +1,62 @@ +const fs = document.querySelector("fieldset"); +const form = document.querySelector("form"); +let init = true; + +function updateHeading(user) { + document.getElementById("username").textContent = `${user.name} ${user.surname}`; +} + +function appendQuestions(question) { + const div = document.createElement("div"); + + const label = document.createElement("label"); + label.for = "id_" + question.id; + label.textContent = question.question; + div.appendChild(label); + + if (question.type === "file" && question.answer) { + const img = document.createElement("img"); + img.src = "uploads/" + question.answer; + img.alt = "Image"; + div.appendChild(img); + } + + const field = document.createElement("input"); + field.id = "id_" + question.id; + field.name = question.id; + if (question.answer !== undefined) init = false; + field.value = question.answer; + field.placeholder = question.question; + field.type = question.type; + if (question.type === "file") field.accept = "image/*"; + + div.appendChild(field); + fs.insertBefore(div, fs.querySelector("button")); +} + +form.addEventListener("submit", async (evt) => { + evt.preventDefault(); + const url = init ? "api/add" : "api/update"; + const method = init ? "POST" : "PUT"; + + const inputs = form.querySelectorAll("input"); + const body = new FormData(); + for (const input of inputs) { + if (input.type !== "file") body.append(input.name, input.value); + else body.append(input.name, input.files[0] ?? "dbg-image"); + } + + const resp = await fetch(url, { method, body }); + const res = await resp.text(); + if (res !== "ok") alert("AHHHH"); +}); + +fetch("api/user") + .then((response) => response.json()) + .then(updateHeading) + .catch(console.error); + +fetch("api/questions") + .then((response) => response.json()) + .then((response) => response.forEach(appendQuestions)) + .catch(console.error); |