Home >Web Front-end >JS Tutorial >How to Transmit 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:
Convert the form data into an array using jQuery's serializeArray() method and then stringify it into JSON.
var formData = JSON.stringify($("#myForm").serializeArray());
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="{"first_name":"binchen","last_name":"heris"}">
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']);
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!