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