Greetings to all the listeners, this is my first time reaching out for help.
I have put together a form and I am making a fetch request to my database system (Xano). Here is a snippet of how my JSON object looks:
{
"job_type": "full-time",
"job_title": "3D Art Director",
"job_location": "remote",
"job_level": "senior",
"salary": "$600 day"
}
However, Xano requires the data to be nested one level deeper inside "data", otherwise I am unable to access it using dot notation...
{
"data": {
"job_type": "full-time",
"job_title": "3D Art Director",
"job_location": "remote",
"job_level": "senior",
"salary": "$600 day"
}
}
Below is the JavaScript code I am using. Can anyone guide me on how and where to place the JSON response inside "data:"{} ? (I am new to JavaScript and my code is a mix of different sources as I am learning!)
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('jobForm').addEventListener('submit', handleForm);
});
function handleForm(ev) {
ev.preventDefault();
let jobForm = ev.target;
let fd = new FormData(jobForm);
//look at all the contents
for (let key of fd.keys()) {
console.log(key, fd.get(key));
}
let json = convertFD2JSON(fd);
//send the request with the formdata
let url = 'https://hookb.in/eKjeKejY6NhlaRPldLNP';
let h = new Headers();
h.append('Content-Type', 'application/json');
let req = new Request(url, {
mode: 'cors', // no-cors, *cors, same-origin
headers: h,
body: json,
method: 'POST',
});
fetch(req)
.then((res) => res.json())
.then((data) => {
console.log('Response from server');
console.log(data);
})
.catch(console.warn);
}
function convertFD2JSON(formData) {
let obj = {};
for (let key of formData.keys()) {
obj[key] = formData.get(key);
}
return JSON.stringify(obj);
}