Home > other >  Send HTML Form Data as a file.json file to REST API using Javascript
Send HTML Form Data as a file.json file to REST API using Javascript

Time:08-17

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": "[email protected]"
}

NOTE: I can't create a data.json in a local system server file and store it locally and send.

CodePudding user response:

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.

  • Related