"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-22
Browse:912

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 ...
... // Code to display response ...

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 ...
... // Code to display response ...

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)
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3