Sometimes, we want to send a JSON object using HTML form data with JavaScript.
In this article, we’ll look at how to send a JSON object using HTML form data with JavaScript.
How to send a JSON object using HTML form data with JavaScript?
To send a JSON object using HTML form data with JavaScript, we use fetch
.
For instance, we write
formElem.onsubmit = async (e) => {
e.preventDefault();
const form = document.querySelector("#formElem");
const data = {
firstname: form.querySelector('input[name="firstname"]').value,
lastname: form.querySelector('input[name="lastname"]').value,
age: 5,
};
const response = await fetch("http://localhost:8482/decode", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
const text = await response.text();
document.querySelector("#decoded").innerHTML = text;
};
to set the form element’s formElement
‘s onsubmit
property to a function that’s called when we submit the form.
In it, we call preventDefault
to stop the default submit behavior.
And then we call fetch
with JSON string we get from the data
object as the request body.
We set "Content-Type"
to "application/json"
to submit data as JSON.
data
has the input values in the object.
We get the response body as a text string with response.text
.
Conclusion
To send a JSON object using HTML form data with JavaScript, we use fetch
.