I am trying to transfer some data from PHP to javascript in json format. The data is actually two fields of a database table, 'humidity' & 'temperature'. After fetching the data from database in php in the form of an array ($wData), I encode it into json using json_encode, get the reference in a js var (WData) and pass it to a js function as parameter (jData).
The data after being received in js function appears fine. But when I try to extract the 'humidity'´or 'temperature' values from it using jData.humidity OR jData.temperature, it shows 'undefined' result in console. One more thing is that the 'humidity'´or 'temperature' variables do not appear in the IDE that they should after I write 'jData.'
Though if I put jData[0], it shows values of both variables. I need to get values of both variables separately because I need to use them to display their own values in a chart.
But as results show that data is at least received. So my question is how to get values of both 'humidity' & 'temperature' in different variables like ones are in my js code.
Here is my code:
PHP CODE
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$WData = $stmt->fetchAll();
/*
echo "<pre>".print_r($WData, true)."</pre>";
die();
*/
?>
<script>
var WData = <?php print_r(json_encode($WData));?>;
// console.log(WData);
dspChrt(WData);
</script>
JS CODE
function dspChrt(jData) {
//jData = JSON.parse(wData);
console.log(jData[0]); //outputs value
console.log(jData.humidity); //outputs 'undefined'
hum = jData.humidity;
tem = jData.temperature;
humArray.shift();
humArray.push(hum);
temArray.shift();
temArray.push(tem);
".print_r($WData, true).""; die();
Array
(
[0] => Array
(
[humidity] => 77.7
[temperature] => 22.1
)
[1] => Array
(
[humidity] => 81.7
[temperature] => 28.1
)
[2] => Array
(
[humidity] => 67.21
[temperature] => 28.9
)
[3] => Array
(
[humidity] => 11.11
[temperature] => 22.11
)
[4] => Array
(
[humidity] => 15
[temperature] => 77.7
)
[5] => Array
(
[humidity] => 15
[temperature] => 77.7
)
console.log(jData); output
[0…999]
[0…99]
0: Object { humidity: "77.7", temperature: "22.1" }
1: Object { humidity: "81.7", temperature: "28.1" }
2: Object { humidity: "67.21", temperature: "28.9" }
3: Object { humidity: "11.11", temperature: "22.11" }
4: Object { humidity: "15", temperature: "77.7" }
5: Object { humidity: "15", temperature: "77.7" }
console.log(jData[0]); output
{
"humidity": "77.7",
"temperature": "22.1"
}
console.log(jData.humidity) output
undefined
console.log(jData.humidity[]); output
SyntaxError: expected expression, got ']'