Home >Web Front-end >JS Tutorial >How Can You Send Form Data in JSON Format?
How to Send Form Data as JSON Object
When crafting HTML forms, it's often necessary to send data in a structured format such as JSON. To facilitate this, let's explore how to convert form data into a JSON object and transmit it to the server.
Convert Form Data to JSON (Client-Side)
To convert form data into a JSON object:
Example:
<br><script type="text/javascript"><br> const form = document.getElementById("myForm");</p> <p>form.addEventListener("submit", function(e) {</p> <pre class="brush:php;toolbar:false">e.preventDefault(); const formData = new FormData(form); const json = JSON.stringify(formData.entries());
});
Setting Headers and Sending JSON to Server (Server-Side)
Once you have the JSON string, you can send it to the server using XMLHttpRequest or any preferred network request method. Remember to set the appropriate headers for JSON data:
<br>xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');<br>
Example (Using XMLHttpRequest):
const xhr = new XMLHttpRequest();
xhr.open("POST", "myUrl", true);<br>xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');<br>xhr.send(json);
Handling Received JSON Data on Server
On the server side, you can parse the received data as a JSON object and access its properties accordingly.
Example (Using Node.js):
<br>const body = request.body.toString();<br>const data = JSON.parse(body);</p> <p>console.log(data.first_name);<br>
The above is the detailed content of How Can You Send Form Data in JSON Format?. For more information, please follow other related articles on the PHP Chinese website!