Home > Backend Development > PHP Tutorial > How to Send JSON Data from JavaScript to PHP: Two Effective Approaches?

How to Send JSON Data from JavaScript to PHP: Two Effective Approaches?

Patricia Arquette
Release: 2024-11-14 12:55:02
Original
240 people have browsed it

How to Send JSON Data from JavaScript to PHP: Two Effective Approaches?

Sending JSON Data from Javascript to PHP

The challenge arises when attempting to relay JSON data from a browser's Javascript environment to a server where PHP will interpret it. To address this, two approaches have proven effective:

Version 1: Leveraging application/json Request Header

  1. Convert the Javascript object into a JSON string using JSON.stringify().
  2. Utilize XMLHttpRequest to dispatch the JSON string to the server.
  3. On the PHP end, retrieve the raw POST data using file_get_contents('php://input').

Version 2: Employing application/x-www-form-urlencoded

  1. Compose a standard POST string using the format "variable_name=value&variable_name_2=value_2".
  2. In Javascript, assign this string to str_json.
  3. In PHP, PHP's $_POST array will populate upon receiving the POST data.

Pitfall to Avoid

Initially, attempting to convey JSON strings with the incorrect request header can lead to difficulties. Using application/x-www-form-urlencoded with the $_POST array in PHP will result in an empty array. Conversely, utilizing application/json requires accessing raw POST data via php://input.

References

  • [How to access POST data in PHP?](https://stackoverflow.com/questions/4199290/how-to-access-post-data-in-php)
  • [IETF RFC 4627: The application/json Media Type for JavaScript Object Notation (JSON)](http://www.ietf.org/rfc/rfc4627.txt)

The above is the detailed content of How to Send JSON Data from JavaScript to PHP: Two Effective Approaches?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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