I have been searching for hours and can't put this to work...
This is my first website, I have a Google gauge that need to ask a database for the value that it should put on the gauge. I know how to ask the database and how to update the gauge, the problem is how should I pass the echo variable from the php file to the javascript file. (The php code need to be in a separate file or otherwise the google gauges won't display).
You can check a actual version of the website here (At the moment the gauges are static).
PHP code:
<?php
$DB_NAME = 'TSB';
$DB_HOST = 'db.tecnico.ulisboa.pt';
$DB_USER = 'xxxxxxxxx';
$DB_PASS = 'xxxxxxxxx';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS);
if (mysqli_connect_errno()) {
printf("Connect failed: %s
", mysqli_connect_error());
exit();
}
$mysqli->query('USE xxxxxxxxxxx;');
$result = $mysqli->query('SELECT SOC FROM TSB ORDER By time DESC LIMIT 1;');
$row = $result->fetch_array();
$soc = $row['SOC'];
echo $soc;
?>
The output of the echo is an int, or at least came as one from the database.
What I'm trying in the javascript file:
function SOC() {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['SOC', 0]
]);
var options = {
width: 250, height: 250,
redFrom: 0, redTo: 10,
yellowFrom: 10, yellowTo: 25,
minorTicks: 5,
majorTicks: ['0','25','50','75','100']
};
var formatter = new google.visualization.NumberFormat({
suffix: '%',
fractionDigits: 0
});
formatter.format(data, 1);
var chart = new google.visualization.Gauge(document.getElementById('SOC'));
chart.draw(data, options);
setInterval(function() {
var socPHP;
$.ajax({
url: 'soc.php',
type: 'get',
dataType:'text',
// I don't know how to properly put the $soc from php in a javascript variable
});
data.setValue(0, 1, 100); // 100 should be replaced by the value
//that came from the php file and the variable should be an INT
chart.draw( data, options);
}, 3000);
}
UPDATE After Tina Suggestion:
<?php
$DB_NAME = 'TSB';
$DB_HOST = 'db.tecnico.ulisboa.pt';
$DB_USER = 'xxxxx';
$DB_PASS = 'xxxxx';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS);
if (mysqli_connect_errno()) {
printf("Connect failed: %s
", mysqli_connect_error());
exit();
}
$mysqli->query('USE xxxxxx;');
$result = $mysqli->query('SELECT SOC FROM TSB ORDER By time DESC LIMIT 1;');
$row = $result->fetch_array();
$soc = $row['SOC'];
?>;
function SOC() {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['SOC', 0]
]);
var options = {
width: 250, height: 250,
redFrom: 0, redTo: 10,
yellowFrom: 10, yellowTo: 25,
minorTicks: 5,
majorTicks: ['0','25','50','75','100']
};
var formatter = new google.visualization.NumberFormat({
suffix: '%',
fractionDigits: 0
});
formatter.format(data, 1);
var chart = new google.visualization.Gauge(document.getElementById('SOC'));
chart.draw(data, options);
setInterval(function() {
data.setValue(0, 1, <?php echo $soc; ?>);
chart.draw( data, options);
}, 3000);
}