Home  >  Article  >  Web Front-end  >  How to Transmit a JSON Object via HTML Form Data?

How to Transmit a JSON Object via HTML Form Data?

Susan Sarandon
Susan SarandonOriginal
2024-10-19 12:01:30617browse

How to Transmit a JSON Object via HTML Form Data?

Transmitting a JSON Object via HTML Form Data

When submitting a form, the data is typically sent as individual form fields. However, if you want to send data as a JSON object, you can utilize the following methods:

Method 1: FormData Array Serialization

Convert the form data into an array using jQuery's serializeArray() method and then stringify it into JSON.

var formData = JSON.stringify($("#myForm").serializeArray());

Method 2: Hidden Text Area

Create a hidden text area within the form and set its value to the JSON stringified form data. This method allows you to access the data on the server side after form submission.

<input type="hidden" name="data" value="{&quot;first_name&quot;:&quot;binchen&quot;,&quot;last_name&quot;:&quot;heris&quot;}">

Server-Side Decoding

If the JSON data is transmitted as part of a regular form submission, it needs to be decoded on the server side. For example, in PHP:

$data = json_decode($_POST['data']);

XHR Error Resolution

In your code, the issue may lie in neglecting to set the Content-Type header explicitly to application/json. The corrected code should be:

xhr.setRequestHeader('Content-Type', 'application/json');

The above is the detailed content of How to Transmit a JSON Object via HTML Form Data?. 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