Reputation: 170
I am having some issues being able to see the array variables echoing in PHP, I have tried numerous things, and I know that the array is being sent to the PHP file via JSON and in a stringify version.
I can write the data to a log file and the data that is displayed in the file for the variable: $datastripped is as follows
{"supplements":[{"supplement":"1","dose":"2","dosewieght":"mg"}]}
the $data variable does not write to the log file no matter how I code it.
I have tried $data, $data[0], $data[0]['supplement'],$data['supplements']['supplement'] and many other combinations.
The information I have found on JSON and that has worked for others does not appear to work for me.
*** I am doing this inside WordPress as well, but have verified that the data is correctly getting to the php function, but can not echo individual items out
Here is the Javascript:
var supplist = {supplements:[]};
supplist.supplements.push({supplement:supplement, dose:dose, dosewieght:doseweight});
$( "#supplementsave" ).click(function(){
var jsonsupparray = JSON.stringify(supplist);
event.preventDefault();
jQuery.ajax({
type: "POST",
dataType:"JSON",
url: myajax.ajax_url,
data:{
data:jsonsupparray,
action: "addsupplements"
},
cache:false,
success: function(data){
console.log("success");
},
});
Here is the PHP:
$datastripped =stripslashes($_POST['data']);
$data = json_decode($datastripped, true); //Data Not Beign shown
foreach($data as $value){
echo $value['supplement'];
}
Upvotes: 0
Views: 55
Reputation: 156
You also need to put single quotes, when you push data in your supplist.
supplist.supplements.push({'supplement':'supplement', 'dose':'dose', 'dosewieght':'doseweight'});
Otherwise it throws javascript error that supplement is not defined, because it treats supplement as variable, not as a string.
Now in your php code You need to decode and your json and iterate.
Upvotes: 3
Reputation: 3009
Just it
<?php
$datastripped = '{"supplements":[{"supplement":"1","dose":"2","dosewieght":"mg"}]}';
$data = json_decode($datastripped, true);
// print_r($data['supplements']);
foreach ($data['supplements'][0] as $key => $value) {
echo $key.' '.$value.'<br>';
}
?>
You will get
supplement 1
dose 2
dosewieght mg
If you want call one parameter
echo $data['supplements'][0]['supplement'];
echo $data['supplements'][0]['dose'];
echo $data['supplements'][0]['dosewieght'];
Upvotes: 1