Looking a solution to take html form data and transform it into JSON file (data.json) using JavaScript.
Currently I am using below HTML & JavaScript Code to send the data in JSON format:
<body>
<form id="profile-form">
<input type="text" id="name" name="name" placeholder="Name">
<input type="email" id="email" name="email" placeholder="Email Address">
<button>Submit</button>
</form>
<script>
const form = document.querySelector('#profile-form');
form.addEventListener('submit', (e) => {
e.preventDefault();
const name = document.querySelector('#name');
const email = document.querySelector('#email');
const fd = new FormData();
fd.append('name', name.value);
fd.append('email', email.value);
fetch('https://webhook.site/2d525f79-301f-4a50-b700-5ee3ba01a05c', {
method: 'POST',
mode: 'no-cors',
body: JSON.stringify(Object.fromEntries(fd)),
dataType: 'json',
headers: {
'Content-Type': 'application/json'
//'Content-Type': 'multipart/form-data',
}
}).then(res => res.json())
.then(json => console.log(json))
.catch(err => console.error(err));
});
</script>
</body>
Now I want both name and email should be send it as data.json in JSON object format to the REST API End URL.
{
"name": "abc",
"email": "abc@gmail.com"
}
NOTE: I can't create a data.json in a local system server file and store it locally and send.