Home > Backend Development > PHP Tutorial > How to Send JSON Data from JavaScript to PHP: Which Header is Right for You?

How to Send JSON Data from JavaScript to PHP: Which Header is Right for You?

DDD
Release: 2024-11-13 04:10:02
Original
507 people have browsed it

How to Send JSON Data from JavaScript to PHP: Which Header is Right for You?

How to Send JSON Data from JavaScript to PHP

When developing web applications, you may encounter the need to send JSON data from JavaScript in the browser to a PHP server. This article explores two methods of achieving this:

Version 1: Using the "application/json" Header

  1. Convert your JavaScript object to a JSON string using JSON.stringify().
  2. Create an AJAX request using XMLHttpRequest and set the Content-type header to "application/json."
  3. Send the JSON string to the PHP server.
... // Code displaying result ...
Copy after login
Copy after login
... // Code to display response ...
Copy after login
Copy after login

Version 2: Using the "application/x-www-form-urlencoded" Header

  1. Create a URL-encoded string of your JSON object using the "json_string=" prefix.
  2. Set the Content-type header to "application/x-www-form-urlencoded."
  3. PHP can then populate the $_POST array with your JSON object.
... // Code displaying result ...
Copy after login
Copy after login
... // Code to display response ...
Copy after login
Copy after login

Pitfall to Avoid

When using the "application/x-www-form-urlencoded" header, PHP cannot directly access the JSON string from the $_POST array. Instead, use file_get_contents('php://input') to access the raw POST data. Conversely, when using the "application/json" header, the raw POST data must be accessed from php://input, not $_POST.

References

  • [How to access POST data in PHP?](How to access POST data in PHP?)
  • [Details on the application/json type](http://www.ietf.org/rfc/rfc4627.txt)

The above is the detailed content of How to Send JSON Data from JavaScript to PHP: Which Header is Right for You?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template