Long time listener, first time caller.
I’ve created a form and sending a fetch request to my database (Xano). My JSON object looks like the below snippet.
JavaScript
x
8
1
{
2
"job_type": "full-time",
3
"job_title": "3D Art Director",
4
"job_location": "remote",
5
"job_level": "senior",
6
"salary": "$600 day"
7
}
8
But Xano needs it to be one level deeper inside “data”, otherwise I can’t map things up with dot notation…
JavaScript
1
10
10
1
{
2
"data": {
3
"job_type": "full-time",
4
"job_title": "3D Art Director",
5
"job_location": "remote",
6
"job_level": "senior",
7
"salary": "$600 day"
8
}
9
}
10
My JS is below. So where and how can I make the JSON response sit inside “data:”{} ? (I am a complete JS Noob and my code is a Frankenstein monster from various sources as I learn!)
JavaScript
1
43
43
1
document.addEventListener('DOMContentLoaded', () => {
2
document.getElementById('jobForm').addEventListener('submit', handleForm);
3
});
4
5
function handleForm(ev) {
6
ev.preventDefault();
7
let jobForm = ev.target;
8
let fd = new FormData(jobForm);
9
10
//look at all the contents
11
for (let key of fd.keys()) {
12
console.log(key, fd.get(key));
13
}
14
let json = convertFD2JSON(fd);
15
16
//send the request with the formdata
17
let url = 'https://hookb.in/eKjeKejY6NhlaRPldLNP';
18
let h = new Headers();
19
h.append('Content-Type', 'application/json');
20
21
let req = new Request(url, {
22
mode: 'cors', // no-cors, *cors, same-origin
23
headers: h,
24
body: json,
25
method: 'POST',
26
});
27
28
fetch(req)
29
.then((res) => res.json())
30
.then((data) => {
31
console.log('Response from server');
32
console.log(data);
33
})
34
.catch(console.warn);
35
}
36
37
function convertFD2JSON(formData) {
38
let obj = {};
39
for (let key of formData.keys()) {
40
obj[key] = formData.get(key);
41
}
42
return JSON.stringify(obj);
43
}
Advertisement
Answer
You can do something like :
JavaScript
1
10
10
1
function convertFD2JSON(formData) {
2
let obj = {
3
data: {}
4
};
5
for (let key of formData.keys()) {
6
obj.data[key] = formData.get(key);
7
}
8
return JSON.stringify(obj);
9
}
10