Home  >  Article  >  Web Front-end  >  How to Send Form Data as a JSON Object Using AJAX?

How to Send Form Data as a JSON Object Using AJAX?

DDD
DDDOriginal
2024-10-19 12:17:30840browse

How to Send Form Data as a JSON Object Using AJAX?

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:

  1. 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>
  1. 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>
  1. 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>
  1. Send JSON-encoded Data:

    Send the JSON-encoded form data to the server using xhr.send():

<code class="javascript">xhr.send(formData);</code>
  1. 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!

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