Home > Web Front-end > JS Tutorial > body text

How to Transmit a JSON Object via HTML Form Data?

Susan Sarandon
Release: 2024-10-19 12:01:30
Original
615 people have browsed it

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());
Copy after login

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;}">
Copy after login

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']);
Copy after login

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');
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!