0

I am creating data in JavaScript which I want to send as an object over AJAX and then access its content in PHP. I have tried so many approaches that I found online but none of them seem to give me more than an empty result in PHP.

Here is my code on the JS side:

myData = {};
myData['a'] = ["1", "2"];
myData['b'] = "3";

jQuery.ajax({
    type: "POST",
    url: my_ajax_site_url,  
    dataType: 'json',
    data: {
        action: "my_php_function",
        inputData: JSON.stringify(myData),
    },
    success: function(response) { 
    },
});

JSON.stringify(myData) gives me the following result when I console.log:

{"a":["1", "2"],"b":"3"}

Then on the PHP side I have tried to access the data through e.g. json_decode like this:

$data = json_decode($_POST['inputData']);
$a = $data['a'];

But $a is always empty.

If I send just a string as inputData I can then easily access it as $a = $_POST['inputData'] and $a then gives me that string. So I know it goes to the function correctly and it works in the general case. I just can't seem to grasp how to do it with an object.

**How can I send my JS object/JSON string over AJAX and access it in PHP? **

eligolf
  • 1,682
  • 1
  • 6
  • 22
  • Try `json_decode($_POST['inputData'], true);`. Passing `true` as the second argument will return the JSON object as an array. If you omit it, you'll get an object back and then need to access the data like this: `$data->a` instead of `$data['a']`. – M. Eriksson Feb 28 '23 at 06:28
  • Does this answer your question? [How to extract and access data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-to-extract-and-access-data-from-json-with-php) – M. Eriksson Feb 28 '23 at 06:30

1 Answers1

0

I finally found what was wrong. Apparently $_POST['inputData'] gets backslashes to its double quotes which made json_decode fail. The string in PHP looks like this instead:

{\"a\":[\"1\", \"2\"],\"b\":\"3\"}

I first had to remove all backslashes, json_decode and then access it like @M.Eriksson said in the comments:

$data = json_decode(stripslashes($_POST['inputData']));
$data->a;
eligolf
  • 1,682
  • 1
  • 6
  • 22
  • PHP generally **won't** do that under normal circumstances. It will if you have Magic Quotes turned on, but you can't turn it on in PHP 5.4 (which hit end of life in 3 Sep 2015 ) or newer. This suggests you are using a **horribly** out of date and insecure version of PHP that you desperately need to upgrade. – Quentin Mar 28 '23 at 14:44
  • @Quentin, No I use PHP 8.something. – eligolf Mar 28 '23 at 16:25