1

I have an onclick button that sends a JS object to my PHP via the following AJAX (data is the name of my object):

function send_to_php() {
$(document).ready(function() {
// pt_packet = JSON.stringify(data)
console.log(data)
var request = $.ajax({
    url: "post_results.php",
    type: 'POST',
    data: (data),
    success: function(result) {
    $("#note").append(result)}})
})}

The problem is when I try to sanitize the data, I the var_dump I get is only the first array and the rest of the information is gone:

array(1) { ["{"Cheif_Complaint":"]=> array(1) { [""Mood issues""]=> string(0) "" } }

Yet this is the information I send: My JS object

I've dropped trying to sanitize the data, but now it looks like I'm having to var_export every single array and then use RegEx to get rid of the "array => (" stuff that I'm left with from var_export. Is there not an easier way to sent a JS object and work with it in PHP?

Austin
  • 103
  • 10

1 Answers1

2

You had the right idea in your commented line of converting the object into a JSON string. This is how you should make the request

$.ajax({
    url: 'post_results.php',
    type: 'POST',
    data: JSON.stringify(data),
    contentType: 'application/json'
})

In your PHP script post_results.php you need to read the raw body of the POST request. You can do this by reading the PHP input stream php://input and then decoding the raw JSON string. Here is an example

$rawJsonString = file_get_contents("php://input");
$jsonData      = json_decode($rawJsonString, true);

The result should be in $jsonData to have the same structure as your JS object.

Pablo
  • 5,897
  • 7
  • 34
  • 51
  • Is ```php://input``` a global thing or is it supposed to be the path of my index file that sends the POST? When I do the steps you pointed out and var_dump($jsonData), I get nothing. – Austin Aug 07 '20 at 03:07
  • Are you dumping this in your `post_results.php` script? `php://input` is not a global, you can think of it as an internal address in PHP. In contrast if you you would do something like `file_get_contents("https://google.com")` you can get the google home page HTML. – Pablo Aug 07 '20 at 03:35
  • `$_POST` is meant to handle forms. So when you send other kinds of data, like JSON, then you need to use `php://input` see https://stackoverflow.com/a/8893792/1497533 – ippi Aug 07 '20 at 03:54