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
... // Code displaying result ...
... // Code to display response ...
Version 2: Using the "application/x-www-form-urlencoded" Header
... // 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
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!