How to Send Form Data as JSON Object Using AJAX
When a user submits an HTML form, you may want to send its data to the server as a JSON object for convenient processing. Here's how to achieve this using AJAX:
Create a Form and Submit Handler:
Define an HTML form with text input fields for collecting user data. Add an onclick event handler to the submit button that handles form submission.
<code class="html"><form action="myurl" method="POST" name="myForm"> <label for="first_name">First Name:</label> <input type="text" name="first_name" id="fname"> <label for="last_name">Last Name:</label> <input type="text" name="last_name" id="lname"> <input type="submit" value="Submit" onclick="submitform()"> </form></code>
Capture Form Data in JavaScript:
Inside the submitform() function, retrieve the complete form data as an array using jQuery's serializeArray() method:
<code class="javascript">var formData = JSON.stringify($("#myForm").serializeArray());</code>
AJAX Request with JSON Content Type:
Create an XMLHttpRequest object, specify the POST method and endpoint URL, and set the Content-Type header to "application/json":
<code class="javascript">var xhr = new XMLHttpRequest(); xhr.open("POST", form.action, true); xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');</code>
Send JSON-encoded Data:
Send the JSON-encoded form data to the server using xhr.send():
<code class="javascript">xhr.send(formData);</code>
Handle Server Response:
Implement the onload event listener to handle the server response and perform necessary actions, such as displaying a success message or redirecting to another page.
By following these steps, you can send JSON objects containing form data to your server for efficient and versatile processing.
The above is the detailed content of How to Send Form Data as a JSON Object Using AJAX?. For more information, please follow other related articles on the PHP Chinese website!