autonomous.contact/public/js/smartforms.js

77 lines
1.6 KiB
JavaScript
Raw Normal View History

document.addEventListener("DOMContentLoaded", () => {
/* make all forms semi-smart */
2025-07-04 14:51:49 -07:00
const forms = document.querySelectorAll("form[data-smart]");
for (const form of forms) {
const script = form.querySelector("script");
form.onsubmit = async (event) => {
event.preventDefault();
const url = form.action;
const method = form.dataset.method ?? "POST";
const json = {};
const form_data = new FormData(form);
for (const [key, value] of form_data.entries()) {
const elements = key.split(".");
let current = json;
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;
}
2025-07-04 14:51:49 -07:00
console.dir({
method,
form,
json,
2025-07-04 14:51:49 -07:00
});
try {
// TODO: send session header
2025-07-04 14:51:49 -07:00
const options = {
method,
headers: {
Accept: "application/json",
},
2025-07-04 14:51:49 -07:00
};
if (["POST", "PUT", "PATCH"].includes(method)) {
options.json = json;
2025-07-04 14:51:49 -07:00
}
const response = await api.fetch(url, options);
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);
}
};
}
});