0

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.

Akash M
  • 488
  • 3
  • 6
  • 18

1 Answers1

1

You can create your own File object using the JSON string and send that.

form.addEventListener("submit", async (e) => {
  e.preventDefault();

  // Capture form data
  const form = new FormData(e.target);

  // Create a File
  const file = new File(
    [JSON.stringify(Object.fromEntries(form))],
    "data.json",
    {
      type: "application/json",
    }
  );

  // Create body for posting
  const body = new FormData();
  body.append("file", file); // "file" is the fieldname

  const res = await fetch(
    "https://webhook.site/2d525f79-301f-4a50-b700-5ee3ba01a05c",
    {
      method: "POST",
      body,
    }
  );

  if (!res.ok) {
    throw new Error(`${res.status}: ${await res.text()}`);
  }

  console.log("uploaded", await res.json());
});

Keep in mind that the Fetch options do not include dataType (that one belongs to jQuery) and setting mode: "no-cors" will mean you cannot see or do anything with the response.

Phil
  • 157,677
  • 23
  • 242
  • 245
  • This works perfectly. Thank you so much for the help. I need one more suggestion, I need to hit the REST API with API Key authorization but displaying directly API KEY in the frontend bit risky so any ways to protect API Key and use it while hitting the REST API? – Akash M Aug 17 '22 at 09:20
  • You cannot protect credentials in a browser based application. I would suggest configuring a server-side proxy that can add sensitive data for you. That could also help with any cors problems – Phil Aug 17 '22 at 09:39