The browser Fetch API is used to make requests from a web page on the frontend to an API endpoint on the backend.
On the other hand, the browser FormData API provides a precise way of accessing HTML form fields. These two native support browser APIs make it easy to send requests. Yet to send data as JSON to an API endpoint this requires extra work. In this tutorial, we will explore a step by step procedure on how to capture form field data, format them as JSON data and send it to an API endpoint.
Table of contents
- Prerequisites
- The HTML form template
- Listening for the form submission
- Reading the form field values with the FormData API
- Formating data to JSON and making a POST request
- The complete code
- Handling JSON request body in a Nodejs and Express.js API
- Conclusion
Prerequisites
To follow along with this tutorial a basic knowledge of the following is required:
- HTML, CSS, and JavaScript
- Have Nodejs installed.
- Express.js
- A code editor.
By the end of this tutorial, you should have a working HTML form that sends form data as JSON to an API endpoint. In the process, you will learn how to make use of the native browser Fetch and FormData APIs to achieve this goal. In the end, you will have a simple Express Node.js API which will listen for the request you send and send back the response.
The HTML form template
<form id="sample-form" method="post" action="http://localhost:5500/form"> <h1>Sample Form</h1> <section> <fieldset> <h3>Gender</h3> <ul> <li> <label for="gender_1"> <input type="radio" id="gender_1" name="gender" value="Male" /> Male </label> </li> <li> <label for="gender_2"> <input type="radio" id="gender_2" name="gender" value="Female" /> Female </label> </li> </ul> </fieldset> <p> <label for="user-fullname"> <span>Full Name: </span> <strong><abbr title="required">*</abbr></strong> </label> <input type="text" id="user-fullname" name="username" /> </p> <p> <label for="user-mail"> <span>E-mail: </span> <strong><abbr title="required">*</abbr></strong> </label> <input type="email" id="user-mail" name="usermail" /> </p> <p><button type="submit">Submit Form</button></p> </section></form>
Here we have a form with 2 radio buttons for selecting male or female gender and 2 input fields, for the full name and email address and a button to submit the form.
Listening for the form submission
Getting the form by ID.
//Get the form element by idlet sampleForm = document.getElementById("sample-form");
When the form’s submit button is clicked the browser dispatches an event, which is captured by the form’s submit event listener. Define the event handler for the form when it’s submitted and prevent the default browser behaviour so that you can handle it instead.
//Define the event handler for the form when it's submittedsampleForm.addEventListener("submit", async (e) => { //Prevent browser default behavior e.preventDefault(); // More code here in the next step}
Reading the form field values with the FormData API
The FormData API provides a precise way of accessing the HTML form field values by passing it a reference to the form element by getting the element attached to the event handler. Then get the URL from the form’s action
attribute.
This obtains all the form fields and makes the form field values available as key-value pairs through a FormData instance. Then call the postFormFieldsAsJson()
function (define it in the next step) and pass the url
and the formData
instance as arguments.
//Define the event handler for the form when it's submittedsampleForm.addEventListener("submit", async (e) => { //Prevent browser default behavior e.preventDefault(); //Get the entire form fields let form = e.currentTarget; //Get URL for api endpoint let url = form.action; try { //Form field instance let formFields = new FormData(form); //Call the `postFormFieldsJson()` function let responseData = await postFormFieldsAsJson({ url, formFields }); } catch (error) { // Handle the error here. console.error(`An has occured ${error}`); }}
Formating data to JSON and making a POST request
Passing the FormData
instance directly to fetch
by default, the request body is formatted as “multipart” and the Content-Type
on the request header is set to multipart/form-data
. Convert the FormData instance to a plain object and then into a JSON string.
Create an object from the formData
instance using the Object.fromEntries() method.
Using the JSON.stringify() method then format the plain form data as JSON.
Specify the HTTP request method as POST and using the header field of the Fetch API specify that you are sending a JSON body request and accepting JSON responses back.
Then set the request body as JSON created from the form fields. Now send the request and listen for the response. If the response is OK
return the response body, otherwise throw an error.
/** * Helper function to POST data as JSON with Fetch. */async function postFormFieldsAsJson({ url, formData }) { //Create an object from the form data entries let formDataObject = Object.fromEntries(formData.entries()); // Format the plain form data as JSON let formDataJsonString = JSON.stringify(formDataObject); //Set the fetch options (headers, body) let fetchOptions = { //HTTP method set to POST. method: "POST", //Set the headers that specify you're sending a JSON body request and accepting JSON response headers: { "Content-Type": "application/json", Accept: "application/json", }, // POST request body as JSON string. body: formDataJsonString, }; //Get the response body as JSON. //If the response was not OK, throw an error. let res = await fetch(url, fetchOptions); //If the response is not ok throw an error (for debugging) if (!res.ok) { let error = await res.text(); throw new Error(error); } //If the response was OK, return the response body. return res.json();}
The complete code
This is the full JavaScript code with inline comments from the steps above that:Captures the form fields using the browser FormData API, converts them to JSON and finally send them to an API endpoint using the browser Fetch API.
//Get the form element by idconst sampleForm = document.getElementById("sample-form");//Add an event listener to the form element and handler for the submit an event.sampleForm.addEventListener("submit", async (e) => { /** * Prevent the default browser behaviour of submitting * the form so that you can handle this instead. */ e.preventDefault(); /** * Get the element attached to the event handler. */ let form = e.currentTarget; /** * Take the URL from the form's `action` attribute. */ let url = form.action; try { /** * Takes all the form fields and make the field values * available through a `FormData` instance. */ let formData = new FormData(form); /** * The `postFormFieldsAsJson()` function in the next step. */ let responseData = await postFormFieldsAsJson({ url, formData }); //Destructure the response data let { serverDataResponse } = responseData; //Display the response data in the console (for debugging) console.log(serverDataResponse); } catch (error) { //If an error occurs display it in the console (for debugging) console.error(error); }});/** * Helper function to POST data as JSON with Fetch. */async function postFormFieldsAsJson({ url, formData }) { //Create an object from the form data entries let formDataObject = Object.fromEntries(formData.entries()); // Format the plain form data as JSON let formDataJsonString = JSON.stringify(formDataObject); //Set the fetch options (headers, body) let fetchOptions = { //HTTP method set to POST. method: "POST", //Set the headers that specify you're sending a JSON body request and accepting JSON response headers: { "Content-Type": "application/json", Accept: "application/json", }, // POST request body as JSON string. body: formDataJsonString, }; //Get the response body as JSON. //If the response was not OK, throw an error. let res = await fetch(url, fetchOptions); //If the response is not ok throw an error (for debugging) if (!res.ok) { let error = await res.text(); throw new Error(error); } //If the response was OK, return the response body. return res.json();}
The sample form data (formDataToJsonString
) object sent as JSON;
{ "title": "Male", "username": "gisioraelvis", "usermail": "gisioraelvis@gmail.com"}
Handling JSON request body in a Node.js and Express.js API
Implementing a simple API using Node.js and Express.js, will expose an endpoint where you will be sending the request containing the form data as JSON.
Setting up the API
Node.js should be installed on your computer. To check if it is installed, run the following command:
node -v
Otherwise, install it using the following instructions.
While within the project root folder, run the following npm
command to initialize the Node.js project.
npm init
Fill in the relevant fields, and then proceed to the next steps.
Alternatively, you can opt to auto initialize the project with NPM default values, in that case, run npm init -y
. Check this in-depth npm guide to understand how to use NPM.
npm packages used:
Express - To run the server and expose an endpoint that you will
POST
our request to. Here is a link to learn more about express.js.Nodemon - This dev package ensures the server hot reloads as you make changes, so you don’t have to restart the server each time changes are made.
CORS or Cross-Origin Resource Sharing, allows you to send and accept requests from a different origin, bypassing the default securities applied to RESTful APIs. An awesome article on using cors in express.js.
Installing the necessary dependencies
This is all the steps to install the listed Node.js Packages:
npm install cors express
and
npm install --save-dev nodemon
The Express API/Server code.
let express = require("express");let app = express();var cors = require("cors");//cors to allow cross origin resource sharingapp.use(cors());//Middleware to parse the body of the request as JSONapp.use(express.json());//The API endpoint that the form will POST toapp.post("/formdata-as-json", (request, response) => { //Destructure the request body let resData = { serverData: request.body, }; //Console log the response data (for debugging) console.log(resData); //Send the response as JSON with status code 200 (success) response.status(200).json(resData);});//Start the server on port 5500app.listen(5500, () => console.log(`we're live 🎉`));
Configure the following start scripts in the package.json file.
"dev": "nodemon api"
To start the server run
npm run dev
The console response on the terminal from the API:
The console response on the browser:
Here is the link to the full project on GitHub.
Conclusion
There you have it! A step by step process on how to format form data as JSON using the browser FormData API and POST it using the browser Fetch API to an API endpoint. You can utilize this newly gained knowledge and skills to develop other applications that make use of these powerful native browser APIs.
Happy coding!
Peer Review Contributions by: Jethro Magaji
FAQs
How To Format Form Data as JSON? ›
Using the JSON. stringify() method then format the plain form data as JSON. Specify the HTTP request method as POST and using the header field of the Fetch API specify that you are sending a JSON body request and accepting JSON responses back. Then set the request body as JSON created from the form fields.
How to convert form data to JSON file? ›- Capture the form's submit event and prevent the default submission.
- Convert the form's child elements to JSON.
- Check to make sure only form field elements are added to the object.
- Add a safeguard to only store checkable fields if the checked attribute is set.
HTML to JSON converter uses a DOM parser to extract data from an HTML document, create a JavaScript object from the parsed data, and convert it into JSON format using the JSON. stringify() function.
How to convert form data to JSON in Python? ›If you have a Python object, you can convert it into a JSON string by using the json. dumps() method.
Can we send FormData as JSON? ›Using the JSON. stringify() method then format the plain form data as JSON. Specify the HTTP request method as POST and using the header field of the Fetch API specify that you are sending a JSON body request and accepting JSON responses back. Then set the request body as JSON created from the form fields.
Why use FormData instead of JSON? ›FormData is a bit different than JSON. It can't have nested data, it's just "key value". It can have multiple entries on one key, unlike JSON.
How to convert an object to JSON? ›- Step 1: Create a Maven project. In the first step, we need to create a maven project using eclipse IDE. ...
- Step 2: Add Jackson dependency in pom.xml. ...
- Step 3: Create POJO to convert into JSON. ...
- Step 4: Create a Java class to convert the Java object into JSON.
- Escape quotation marks used around HTML attributes like so <img src=\"someimage.png\" />
- Escape the forward slash in HTML end tags. ...
- This one was totally bizarre. ...
- Be sure to encode any quotation marks that might be included in (bad) HTML content.
POST request to send JSON in a form (multipart/form-data)
You need to enable this by clicking the three dots and enabling Content Type. This will allow you to create a multipart/form-data request with each part having a different content type. Notice how the part with JSON now has its own content type.
- Create a function named “convert”.
- Create a sample JSON data.
- Get the container using getElementByID(“container”) where we will append the table.
- Get the keys of the first object of the JSON data so that we get the headings of the table.
How to convert data into JSON string? ›
Stringify a JavaScript Array
Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(arr); The result will be a string following the JSON notation.
Excel to JSON using VBA code editor
Besides using all these tools, you can use the in-built feature of Excel (VBA code editor) to convert the Excel data to JSON format. Make a code for it and execute the code; it will do the mapping of Excel columns to JSON object keys and convert the data into JSON.
XML File to JSON String in Python
To convert an XML file into a JSON string, we can use the dumps() method defined in the json module. For this, we will first open the XML file in read mode using the open() function. Then, we will read the contents of the XML file as a string using the read() method.
The method attribute specifies how to send form-data (the form-data is sent to the page specified in the action attribute). The form-data can be sent as URL variables (with method="get" ) or as HTTP post transaction (with method="post" ). Notes on GET: Appends form-data into the URL in name/value pairs.
How to save form data in JavaScript? ›- let saveFile = () => {
- // Get the data from each element on the form.
- const name = document. getElementById("txtName");
- const age = document. getElementById("txtAge");
- const email = document. getElementById("txtEmail");
- const country = document. getElementById("selCountry");
- const msg = document.
- Create the form with its inputs and submit input/button as you would normally do.
- Give the form a unique Id.
- Add a submit event listener to the form and pass the event object with it.
- Build the request body in JSON format using the FormData class.
- Add any headers, if needed.
JSON is perfect for storing temporary data. For example, temporary data can be user-generated data, such as a submitted form on a website. JSON can also be used as a data format for any programming language to provide a high level of interoperability.
How to send data in API JSON? ›To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You must also specify the data type using the Content-Type: application/json request header.
Should I use form or JSON? ›So ultimately, the choice rests on the complexity of the object you are sending. If the object is limited to one level deep, use straight name-value-pair; if the object is complex and involves a deeply-nested tree, use JSON.
Which data format is better than JSON? ›YAML, Protobuf, Avro, MongoDB, and OData are the most popular alternatives and competitors to JSON.
What is a better format than JSON? ›
YAML is the most human-readable data serialization format. Many developers consider it easier to learn than JSON because it's written using natural language. YAML is a superset of JSON. It was developed around the same time to handle more kinds of data and offer a more complex but still readable syntax.
How to convert list of object to JSON format? ›An object is an unordered collection of key/value pairs and an array is an ordered sequence of values. We can convert a list to the JSON array using the JSONArray. toJSONString() method and it is a static method of JSONArray, it will convert a list to JSON text and the result is a JSON array.
How to convert data into JSON format in JavaScript? ›JSON.stringify() The JSON.stringify() static method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
How to convert string array into JSON object? ›JS Array to JSON using JSON.
stringify([1, 2, 3, 4, 5]); The JSON. stringify() method converts a JavaScript object, array, or value to a JSON string. If you so choose, you can then send that JSON string to a backend server using the Fetch API or another communication library.
- Store JSON in a database table.
- Query a table for rows storing particular values within a JSON document.
- Create indexes to find these rows efficiently.
- Generate JSON from relational rows and columns.
- window.localStorage - stores data with no expiration date.
- window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)
- Define Queries. We will define two queries. ...
- Generate XML Schema. ...
- Create the Form. ...
- Link to the Database. ...
- Define the SQL Query. ...
- Generate an XML Schema. ...
- Create the Form. ...
- Link to the Database.
As such, we can use form-data for sending large binary or non-ASCII text to the server. The raw data type sends any plain text or JSON to the server, as the name suggests. It supports multiple content types, and Postman will send the raw data without any modifications, unlike with the other data types.
How do I pass form data in POST request? ›To post HTML form data to the server in URL-encoded format, you need to make an HTTP POST request to the server and provide the HTML form data in the body of the POST message in key=value format. You must also specify the data type using the Content-Type: application/x-www-form-urlencoded request HTTP header.
How to post JSON data using REST template? ›To make a POST request with the RestTemplate in JSON, you can use the postForObject() method and pass it the URL of the request, the request body, the response type, and the HttpEntity object that represents the request headers and body.
How to create JSON data in SQL? ›
SQL Server can't generate JSON with FOR JSON AUTO unless it has a schema to build the object from. The SELECT in your INSERT statement is just selecting a couple of variable values when trying to generate the JSON. In the scope of the cursor, SQL Server doesn't have any context in which to generate the JSON object(s).
How to insert JSON data into Datatable? ›- on top of the XAML prepare an empty datatable with the build datatable activity and configure the needed columns.
- use add datarow activity for adding the data to the datatable within the for each after the Multiple Assign activity.
The table is the base JSON object. A table has two properties, headers and rows, which would be an array of header and row objects.
How to convert text to JSON format? ›To change TEXT format to JSON, upload your TEXT file to proceed to the preview page. Use any available tools if you want to edit and manipulate your TEXT file. Click on the convert button and wait for the convert to complete. Download the converted JSON file afterward.
How to send string in JSON format? ›Send JSON Data from the Client Side
Use JSON. stringify() to convert the JavaScript object into a JSON string. Send the URL-encoded JSON string to the server as part of the HTTP Request. This can be done using the HEAD, GET, or POST method by assigning the JSON string to a variable.
MS SQL provided two options for converting data into JSON that is by using FOR JSON AUTO, and FOR JSON PATH.
Can Excel format JSON? ›JavaScript Object Notation (JSON) is a common data format, and you can import it into Excel.
How to convert CSV data into JSON format? ›- Step 1: Select your input. Enter Data.
- Step 2: Choose input options (optional) Input Options. ...
- Step 3: Choose output options (optional) Output Options. ...
- Step 4: Create Custom Output via Template (optional) Modify template below and Press Convert See also CSV Templates. ...
- Step 5: Generate output. Choose Conversion Type:
Excel table data can be represented as an array of objects in the form of JSON.
What is the code for converting XML to JSON? ›JSONObject json = XML. toJSONObject(xml); String jsonString = json. toString(4);
How to convert Python object to JSON file? ›
To dump a Python object to JSON string, you can use the json. dumps() method of the built-in json module. The json. dump() paired method (without the "s") converts the Python object to JSON string and writes it to a file.
How to add JSON language in Notepad ++? ›- Launch Notepad++ on your computer, and then navigate to the Plugins tab from the top toolbar and select Plugins Admin.
- In the Plugins Admin window, type JSON Viewer in the Search box and click on Next.
- Tick the checkbox next to JSON Viewer and click on Install.
A Form Data Format file is a text file that contains a list of form fields and their values. FDFMerge Pro uses the data in FDF files to assemble and fill out forms. There are two kinds of FDF files: Classic—supplies data to fill out an existing form.
What is a FormData file? ›FormData is simply a data structure that can be used to store key-value pairs. Just like its name suggests it's designed for holding forms data i.e you can use it with JavaScript to build an object that corresponds to an HTML form.
How to pass FormData in REST API? ›- Create a web application. Mine is called multiparttest.
- Add an input text element by dragging it from the Component palette. This will store the "name" attribute of our REST API payload.
- Let us add a file picker in order to select a file from the local computer.
FormData: get() method
The get() method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead. Note: This method is available in Web Workers.
First of all, we'll create an empty object and then iterate over the FormData object we've created in the previous section: const formDataObj = {}; myFormData. forEach((value, key) => (formDataObj[key] = value));
How do I save HTML form data to text? ›Step-by-step guide on How to put the HTML form field data in a text file or dot txt file in PHP. Create a PHP file and put the below code and save it. <! DOCTYPE html> <html> <head> <title>Store form data in .
How to convert XML data to JSON data? ›- Select the XML to JSON action from the Tools > JSON Tools menu. ...
- Choose or enter the Input URL of the XML document.
- Choose the path of the Output file that will contain the resulting JSON document.
- Select how you want empty elements to be converted (default is object).
- Upload a PDF file.
- Click to convert the file into JSON.
- Download the converted JSON file.
How to convert data from Excel to JSON? ›
Excel to JSON using VBA code editor
Besides using all these tools, you can use the in-built feature of Excel (VBA code editor) to convert the Excel data to JSON format. Make a code for it and execute the code; it will do the mapping of Excel columns to JSON object keys and convert the data into JSON.
The purpose of the XML to JSON Converter tool is to convert XML (Extensible Markup Language) code into JSON format. JSON is a lightweight data-interchange format, it's useful for exchanging data from client to server, or from server to client.
How to convert data from API to JSON? ›To get JSON from a REST API endpoint, you must send an HTTP GET request to the REST API server and provide an Accept: application/json request header. The Accept: application/json header tells the REST API server that the API client expects to receive data in JSON format.
How to convert PDF to XML JSON? ›- Use the Select tool to mark the content you want to save.
- Right-click the highlighted text.
- Choose Export Selection As.
- Select XML, and click Save.
In Acrobat, open the completed form file. From the All tools menu, select Prepare a form and then from the left panel that opens, select > Export data. In the Export Form Data As dialog box, select the format (FDF, XFDF, XML, or TXT) in which you want to save the form data.
What is a JSON string? ›JSON is purely a string with a specified data format — it contains only properties, no methods. JSON requires double quotes to be used around strings and property names. Single quotes are not valid other than surrounding the entire JSON string.