I want to call the array in php file to javascript file
I did this code but didn’t retrieve the array and there is no error shows:
in data.php:
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "['".$row['time']."',".$row['temp'].",".$row['hum']."],";
}
}
?>
and in script.js:
function drawLineColors() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'time');
data.addColumn('number', 'Temperature');
data.addColumn('number', 'Humidity');
$.get('data.php').then(function(data2){
data.addRows([
[data2],
]);
<?php
echo "<script> // Your JS here </script>"
?>
And be able to have your second script refer to whatever was output by the PHP.
If that’s not working, inspect your page source to find out what is being rendered.
That said, if you find yourself doing this more than very occasionally, I’d look at ways to better structure your code. For example, you could make an Ajax request to a PHP endpoint to grab the data you need for your chart.
google.charts.load('current', {'packages':['corechart', 'line']});
google.charts.setOnLoadCallback(drawLineColors);
function drawLineColors() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'time');
data.addColumn('number', 'Temperature');
data.addColumn('number', 'Humidity');
$.get('data.php').then(function(data2){
data.addRows([data2]);
let rowIndex = data.getNumberOfRows() - 1; //gets the row index of last row
let lastTime = data.getValue(rowIndex, 0); //gets the first column
let lastTemp = data.getValue(rowIndex, 1); //gets second column
let lastHum = data.getValue(rowIndex,2); //gets third column
First, does your query return any data? Test it directly in the browser to see if it is working correctly.
Second, add some debugging to your calling code using something like console.log so that you can see what is happening. Does it even call the PHP code to retrieve the data? Do you need to tell your code that the data coming back is in JSON format?
$.get has optional parameters, such that you can define the return type specifically.
$.get("data.php","json");
I wouldn’t use .then on a request that may eventually require large loads, because it can trigger when the server sends a ‘in progress’ notification; instead look for .done
It was really the JSON.parse I was adding there. I’m not really clued up on Ajax, there seems to be many ways to achieve the same thing - which isn’t necessarily a bad thing, of course.