Sending JSON Data to PHP Using Ajax
Problem:
When attempting to send JSON data to a PHP file via Ajax, the data is not being received and the array $_POST contains empty values.
Resolution:
To resolve this issue, the contentType parameter in the Ajax request should be removed. The contentType option is used when sending raw data to the server, but in this case, the data is already in a valid JSON format. By removing it, the server will automatically handle the JSON data correctly.
Also, the JSON.stringify and json_decode functions are not necessary in this context. Instead, the postData object can be used as the request payload directly.
Updated Ajax Code:
$.ajax({ type: "POST", dataType: "json", url: "add_cart.php", data: {myData: postData}, success: function(data){ alert('Items added'); }, error: function(e){ console.log(e.message); } });
Updated PHP Code:
if(isset($_POST['myData'])){ $obj = $_POST['myData']; // Some PHP operation }
The above is the detailed content of Why is my JSON data not being received by PHP via Ajax?. For more information, please follow other related articles on the PHP Chinese website!