2025-07-01 15:37:35 -07:00
|
|
|
document.addEventListener("DOMContentLoaded", () => {
|
|
|
|
/* make all forms semi-smart */
|
2025-07-04 14:51:49 -07:00
|
|
|
const forms = document.querySelectorAll("form[data-smart]");
|
2025-07-01 15:37:35 -07:00
|
|
|
for (const form of forms) {
|
|
|
|
const script = form.querySelector("script");
|
|
|
|
|
|
|
|
form.onsubmit = async (event) => {
|
|
|
|
event.preventDefault();
|
|
|
|
|
|
|
|
const form_data = new FormData(form);
|
|
|
|
const body = {};
|
|
|
|
for (const [key, value] of form_data.entries()) {
|
|
|
|
const elements = key.split(".");
|
|
|
|
let current = body;
|
|
|
|
for (const element of elements.slice(0, elements.length - 1)) {
|
|
|
|
current[element] = current[element] ?? {};
|
|
|
|
current = current[element];
|
|
|
|
}
|
|
|
|
|
|
|
|
current[elements.slice(elements.length - 1).shift()] = value;
|
|
|
|
}
|
|
|
|
|
|
|
|
const url = form.action;
|
2025-07-04 14:51:49 -07:00
|
|
|
const method = form.dataset.method ?? "POST";
|
2025-07-01 15:37:35 -07:00
|
|
|
|
2025-07-04 14:51:49 -07:00
|
|
|
console.dir({
|
|
|
|
method,
|
|
|
|
form,
|
|
|
|
});
|
2025-07-01 15:37:35 -07:00
|
|
|
try {
|
|
|
|
// TODO: send session header
|
2025-07-04 14:51:49 -07:00
|
|
|
const options = {
|
|
|
|
method,
|
2025-07-01 15:37:35 -07:00
|
|
|
headers: {
|
|
|
|
Accept: "application/json",
|
|
|
|
},
|
2025-07-04 14:51:49 -07:00
|
|
|
};
|
|
|
|
|
|
|
|
if (["POST", "PUT", "PATCH"].includes(method)) {
|
|
|
|
options.headers["Content-Type"] = "application/json";
|
|
|
|
options.body = JSON.stringify(body);
|
|
|
|
}
|
|
|
|
|
|
|
|
const response = await fetch(url, options);
|
2025-07-01 15:37:35 -07:00
|
|
|
|
|
|
|
if (!response.ok) {
|
|
|
|
const error_body = await response.json();
|
|
|
|
const error = error_body?.error;
|
|
|
|
|
|
|
|
if (form.on_error) {
|
|
|
|
return form.on_error(error);
|
|
|
|
}
|
|
|
|
|
|
|
|
alert(error.message ?? "Unknown error!");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const response_body = await response.json();
|
|
|
|
if (form.on_response) {
|
|
|
|
return form.on_response(response_body);
|
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
console.dir({
|
|
|
|
error,
|
|
|
|
});
|
|
|
|
|
|
|
|
if (form.onerror) {
|
|
|
|
return form.onerror(error);
|
|
|
|
}
|
|
|
|
|
|
|
|
alert(error);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
});
|