Home >Backend Development >PHP Tutorial >How to Send JSON Data from JavaScript to PHP?

How to Send JSON Data from JavaScript to PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-11-13 07:31:021022browse

How to Send JSON Data from JavaScript to PHP?

Sending JSON Data from JavaScript to PHP

Transferring JSON data from JavaScript on the browser to a PHP server for parsing can be achieved through several methods.

Method A: Using application/json Header

  1. In JavaScript, convert the object to a JSON string using JSON.stringify().
  2. Send the JSON string to the server using XMLHttpRequest with the application/json header:
request.setRequestHeader("Content-type", "application/json");
request.send(str_json);
  1. On the PHP server, read the raw POST data using file_get_contents('php://input') to obtain the JSON string.

Method B: Using application/x-www-form-urlencoded Header

  1. Convert the JSON object to a standard POST string using JSON.stringify() and the format json_string=....
  2. Send the POST string to the server using XMLHttpRequest with the application/x-www-form-urlencoded header.
  3. In PHP, access the JSON string from the $_POST['json_string'] array. Use json_decode() to parse the retrieved JSON string.

Pitfall:

Attempting to send the JSON string with the application/x-www-form-urlencoded header and then accessing it via $_POST will result in an empty array, as PHP expects data in the yval=xval& format. Therefore, use php://input to access raw POST data when using the application/json header.

Additional Resources:

  • [How to access POST data in PHP](https://www.php.net/manual/en/features.http-post-vars.php)
  • [RFC 4627: The application/json Media Type for JSON](http://www.ietf.org/rfc/rfc4627.txt)

The above is the detailed content of How to Send JSON Data from JavaScript to PHP?. 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