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
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