To send a JSON object using HTML form data with JavaScript, we use fetch
.
For instance, we write
const ajax = async (config) => {
const request = await fetch(config.url, {
method: config.method,
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(config.payload),
});
response = await request.json();
console.log("response", response);
return response;
};
to call fetch
with the URL to make the request to and an object with the headers
and body
.
We set body
to the stringifed JSON object we get with JSON.stringify
to send that as the JSON body.
We set the headers
to the request headers keys and values.
Then we get the JSON response in a promise with request.json
.