Home >Web Front-end >JS Tutorial >How Can You Send Form Data in JSON Format?

How Can You Send Form Data in JSON Format?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-19 12:03:02401browse

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:

  1. Retrieve the form data using JavaScript's FormData object (e.g., const formData = new FormData(form)).
  2. Iterate over the form elements and extract their values into a JSON object (e.g., let json = JSON.stringify(formData.entries())).

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn