Home >Backend Development >PHP Tutorial >How to Decode JSON Data from Ajax in PHP?
Decoding JSON Data from Ajax in PHP
When attempting to send JSON data from an Ajax request to a PHP script, you may encounter an issue where the data is not properly received or parsed. To resolve this, a common question is how to effectively send JSON data from Ajax and decode it in PHP.
Solution
1. Remove Content-Type Header
In the Ajax request, remove the contentType header:
$.ajax({ type: "POST", dataType: "json", url: "add_cart.php", data: {myData:dataString} });
2. Use Direct Variable Assignment
In PHP, access the JSON data directly from $_POST without using json_decode:
if(isset($_POST['myData'])){ $obj = $_POST['myData']; //some php operation }
Reason
The reason the original code was not working is because the contentType header was set to application/json. This indicated to PHP that the data being sent was in JSON format, which is not the case. The data is actually a normal POST query that contains a JSON string.
By removing the contentType header, you are sending the data as a regular POST query and allowing PHP to handle the string conversion automatically.
The above is the detailed content of How to Decode JSON Data from Ajax in PHP?. For more information, please follow other related articles on the PHP Chinese website!