Skip to content

Commit

Permalink
Merge pull request #67 from TheSecretOrganization/form
Browse files Browse the repository at this point in the history
form system
  • Loading branch information
Neffi42 authored Sep 11, 2024
2 parents 0074299 + e757b83 commit 7d648ff
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
1 change: 1 addition & 0 deletions nginx/src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
crossorigin="anonymous"></script>
<script src="/js/router.js"></script>
<script src="/js/core.js"></script>
</body>

</html>
53 changes: 53 additions & 0 deletions nginx/src/js/core.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@

function submitForm(id, oncomplete, onerror) {
let form = document.querySelector(`form#${id}`);
let inputs = document.querySelectorAll(`form#${id} input`);
let values = {};

if (form == undefined || inputs == undefined)
throw new Error(`Unknown form with id ${id}`);

if (!('url' in form.dataset))
throw new Error(`Missing data url in form id ${id}`);
let url = form.dataset.url;

for (let input of inputs)
values[input.id] = input.value

postFetch(url, getCookie('csrftoken'), values)
.then((response) => {
if (response.status == 200)
oncomplete();
else
response.json()
.then(json => onerror(json))
.catch(error => console.error(error));
}).catch(error => console.error(error));
}

function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}

function postFetch(url, csrf, body) {
return fetch(url, {
method: 'POST',
headers: {
'X-CSRFToken': csrf,
'Content-Type': 'application/json',
},
mode: 'same-origin',
body: JSON.stringify(body),
});
}

0 comments on commit 7d648ff

Please sign in to comment.