2023-12-06 08:46:58 +01:00

41 lines
1.1 KiB
JavaScript

//Get the form element by id
const callForm = document.getElementById("call-form");
callForm.addEventListener("submit", async (e) => {
e.preventDefault();
let form = e.currentTarget;
let url = form.action;
try {
let formData = new FormData(form);
console.log(form)
console.log(formData)
let responseData = await postFormFieldsAsJson({ url, formData });
let { serverDataResponse } = responseData;
console.log(serverDataResponse);
} catch (error) {
console.error(error);
}
});
async function postFormFieldsAsJson({ url, formData }) {
let formDataObject = Object.fromEntries(formData.entries());
let formDataJsonString = JSON.stringify(formDataObject);
let fetchOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: formDataJsonString,
};
console.log(fetchOptions);
let res = await fetch(url, fetchOptions);
if (!res.ok) {
let error = await res.text();
throw new Error(error);
}
return res.json();
}