mirror of
https://gitlab.ub.uni-bielefeld.de/sfb1288inf/nopaque.git
synced 2025-06-15 10:30:40 +00:00
Enhance code structure
This commit is contained in:
57
app/static/js/forms/base-form-new.js
Normal file
57
app/static/js/forms/base-form-new.js
Normal file
@ -0,0 +1,57 @@
|
||||
export class BaseForm {
|
||||
constructor(formElement) {
|
||||
this.element = formElement;
|
||||
|
||||
this.element.addEventListener('submit', (event) => {
|
||||
event.preventDefault();
|
||||
this.submit();
|
||||
});
|
||||
console.log("UsernamePostFormInitialized");
|
||||
}
|
||||
|
||||
submit() {
|
||||
let errorTextElements = this.element
|
||||
.querySelectorAll('.supporting-text[data-supporting-text-type="error"]');
|
||||
for (let errorTextElement of errorTextElements) {errorTextElement.remove();}
|
||||
|
||||
const body = new FormData(this.element);
|
||||
const headers = {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json'
|
||||
};
|
||||
const method = this.element.method;
|
||||
|
||||
const fetchPromise = new Promise((resolve, reject) => {
|
||||
fetch(this.element.action, {body: body, headers: headers, method: method})
|
||||
.then((response) => {
|
||||
if (!response.ok) {
|
||||
console.log("reject", response);
|
||||
reject(response);
|
||||
return;
|
||||
}
|
||||
console.log("resolve", response);
|
||||
resolve(response);
|
||||
});
|
||||
});
|
||||
|
||||
fetchPromise
|
||||
.then(
|
||||
(response) => {console.log("Hello from resolve handler");return response.json();},
|
||||
(response) => {
|
||||
console.log("Hello from reject handler 1/2");
|
||||
response.json()
|
||||
.then((errors) => {
|
||||
console.log("Hello from reject handler 2/2");
|
||||
for (let [name, messages] of Object.entries(errors)) {
|
||||
console.log(name, messages);
|
||||
const inputFieldElement = this.element[name].closest('.input-field');
|
||||
for (let message of messages) {
|
||||
const messageHTML = `<span class="supporting-text" data-supporting-text-type="error">${message}</span>`;
|
||||
inputFieldElement.insertAdjacentHTML('beforeend', messageHTML);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
);
|
||||
}
|
||||
};
|
Reference in New Issue
Block a user