How to add latest TimesStamp to Google Gauge - mysql

I need help adding latest TimesStamp to page that displays Google gauge. I have made gauge work and auto refresh without the need to refresh the page, but now I need to display on it, or next to it when the latest entry in database was made (displaying TimesStamp of value that is currently displayed in gauge). Here's my code so far:
Chart.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {
packages: ['gauge']
}).then(function () {
var options = {
width: 800, height: 240,
greenFrom: 98, greenTo: 100,
yellowFrom:90, yellowTo: 98,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
drawChart();
function drawChart() {
$.ajax({
url: 'getdata.php',
dataType: 'json'
}).done(function (jsonData) {
// use response from php for data table
var data = google.visualization.arrayToDataTable(jsonData);
chart.draw(data, options);
// draw again in 5 seconds
window.setTimeout(drawChart, 5000);
});
}
});
</script>
</head>
<body>
<div id="chart_div" style="width: 800px; height: 240px;"></div>
</body>
</html>
And here's getdata.php
<?php
$servername = "localhost";
$username = "u644759843_miki";
$password = "plantaze2020!";
$dbname = "u644759843_plantazeDB";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$conn->set_charset('utf8mb4');
$sql = "SELECT ProductPurity FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
// create data array
$data = [];
$data[] = ["Label", "Value"];
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", (float) $row["ProductPurity"]];
}
mysqli_close($conn);
// write data array to page
echo json_encode($data);
?>

we need to include the timestamp in the data we return from php.
first, add the field to the select statement, here...
$sql = "SELECT ProductPurity, TimesStamp FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
next, we use a variable to save the timestamp...
// create data array
$data = [];
$data[] = ["Label", "Value"];
$stamp = null;
then, in the while loop, we save the value of the timestamp...
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", (float) $row["ProductPurity"]];
$stamp = $row["TimesStamp"]
}
finally, we combine both the chart data and timestamp in an object to send to the page.
$data = array('rows' => $data, 'timestamp' => $stamp);
following is the updated php snippet...
<?php
$servername = "localhost";
$username = "u644759843_miki";
$password = "plantaze2020!";
$dbname = "u644759843_plantazeDB";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$conn->set_charset('utf8mb4');
$sql = "SELECT ProductPurity, TimesStamp FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
// create data array
$data = [];
$data[] = ["Label", "Value"];
$stamp = null;
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", (float) $row["ProductPurity"]];
$stamp = $row["TimesStamp"]
}
mysqli_close($conn);
// write data array to page
$data = array('rows' => $data, 'timestamp' => $stamp);
echo json_encode($data);
?>
then on the html page, we need to adjust how we receive the data...
to receive the chart data, we need to use the 'rows' property from the data.
// use response from php for data table
var data = google.visualization.arrayToDataTable(jsonData.rows); // <-- add .rows
and we can receive the timestamp as follows...
jsonData.timestamp
not sure how you want to display the timestamp, here a <div> is used.
so to update the new <div> element...
document.getElementById('timestamp').innerHTML = jsonData.timestamp;
following the updated html snippet...
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {
packages: ['gauge']
}).then(function () {
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
drawChart();
function drawChart() {
$.ajax({
url: 'getdata.php',
dataType: 'json'
}).done(function (jsonData) {
// use response from php for data table
var data = google.visualization.arrayToDataTable(jsonData.rows);
chart.draw(data, options);
// update timestamp
document.getElementById('timestamp').innerHTML = jsonData.timestamp;
// draw again in 5 seconds
window.setTimeout(drawChart, 5000);
});
}
});
</script>
</head>
<body>
<div id="timestamp"></div>
<div id="chart_div" style="width: 400px; height: 120px;"></div>
</body>
</html>

Related

Cannot open geojson with leaflet

I am converting my data from database to geojson and then i cant open the returned value from ajax into L.geoJson.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link
rel="stylesheet"
href="http://cdn.leafletjs.com/leaflet-0.7/leaflet.css" />
<script
src="http://cdn.leafletjs.com/leaflet-0.7/leaflet.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-ajax/2.1.0/leaflet.ajax.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div id="map" style="width: 600px; height: 400px"></div>
<script type="text/javascript">
<!-- Base Map -->
var map = L.map('map').setView([40.6430126, 22.934004], 14);
mapLink =
'OpenStreetMap';
L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© ' + mapLink + ' Contributors',
maxZoom: 18,
}).addTo(map);
</script>
</body>
</html>
<script>
//Ajax
$.ajax({
method: "GET",
url: "2j.php",
dataType: "json",
}).done(function (data) {
var result = data;
L.geoJson(result).addTo(map);
});
</script>
Php File -> Connection to database and conversation!
<?php
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "basi";
$features = array();
$geojson = array(
'type' => 'FeatureCollection',
'features' => $features
);
$i=1.01;
$conn = new mysqli($servername, $username, $password, $dbname);
// Parse the query into geojson
// ================================================
// ================================================
// Return polygons as GeoJSON
for($i;$i<10;$i++){
$k=floor($i);
$sql = "SELECT x1, y1 FROM afriti where floor(id)=$k";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$feature = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Polygon',
'coordinates' => array((float)$row["x1"], (float)$row["y1"])
));
array_push($features, $feature);
}
}
} echo json_encode($geojson);
?>
I tried just to print something after ajax is done and its doesnt output anything, so either its not ending or something is bad written.
It doesnt print any error messages.
For starters you are missing a parenthesis ) in this line:
'coordinates' => array((float)$row["x1"], (float)$row["y1"]));

Get data from database and append data to aframe

I want to get data from database and append that data to aframe. I did and data is getting from the database but not appending to the aframe scene. Here is my working flow.
This index file:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<a-scene id="scene">
<a-camera id="camera" position="0 0 2" >
</a-camera>
<a-sky color="#000"></a-sky>
</a-scene>
<script>
var ajax = new XMLHttpRequest();
var method = "GET";
var url = "data.php";
var asychronous = true;
ajax.open(method,url,asychronous);
ajax.send();
ajax.onreadystatechange = function(){
if(this.readyState==4 && this.status==200){
var data = JSON.parse(this.responseText);
console.log(data);
var html = "";
var username = "";
for(var i=0;i<data.length;i++){
username = data[i].username;
html += "<a-scene>";
html += +username;
html += "</a-scene>";
}
var totalText1 = document.createElement('a-text');
totalText1.setAttribute('position',{x:0, y:0, z:0});
totalText1.setAttribute('color',"#fff");
totalText1.setAttribute('value',username);
totalText1.setAttribute('scale',{x:1.6, y:1.6, z:1.6});
document.getElementById("scene").appendChild(totalText1);
}
}
</script>
</body>
</html>
Here is data.php file
<?php
$conn = mysqli_connect("localhost","root","","test");
$query = "SELECT * FROM usertest WHERE language='english'";
$result = mysqli_query($conn,$query);
$data = array();
while($row = mysqli_fetch_assoc($result)){
$data = $row;
}
echo json_encode($data);
?>
Data retrieving is okay.But is there any way to append those data to aframe scene?
Double check the entity is actually getting appended to the scene. It looks right. Check the Inspector (ctrl/alt/i) or DOM Inspector or query selector from console. The 0/0/0 position might just make it hard to see.

How to display ganttchart with mysql database values in laravel?

I want to make a ganttchart, where I can retrieve data from database using mysql.
Highcharts do no include ganttchart, so i tried google charts. I am able to retrieve values from database and its can be seen in the page source, but not getting the output.
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1.1", {packages:["gantt"]});
google.setOnLoadCallback(drawChart);
<?php
$con = mysqli_connect("localhost","root","","db1") or die("could not connect");
$query= "select * from view_chart";
$qresult=mysqli_query($con,$query);
$results = array();
while($res = mysqli_fetch_array($qresult))
{
$results[] = $res;
}
$gan_data = array();
foreach($results as $result)
{
$gan_data[] = ($result['Brands']);
$gan_data1[] = ((int)$result['ratings']);
$gan_data2[] = ((int)$result['bigbazar']);
}
$gan_data = json_encode($gan_data);
$gan_data1 = json_encode($gan_data1);
$gan_data2 = json_encode($gan_data2);
mysqli_free_result($qresult);
?>
function drawChart() {
// var container = document.getElementById('gantt');
//var chart =new google.visualization.GanttChart(container);
alert('hello');
var data = new google.visualization.arrayToDataTable(<?=$gan_data?>);
data.addColumn( type: 'string', id: 'Brands' );
data.addColumn( type: 'number', id: 'ratings' );
data.addColumn( type: 'number', id: 'bigbazar' );
data.addRows([
<?php echo $gan_data; ?>,
<?php echo $gan_data1; ?>,
<?php echo $gan_data2; ?>]);
var options = {
height: 275
};
var chart = new google.visualization.GanttChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>

PHP MySQL Data To AngularJS

I am using this code to pull data from a MySQL.
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
var icon = data[1];
var english = data[2];
var british = data[3];
$('#output').html("<b>id: </b>"+id+"<b> icon: </b>"+icon+"<b> english: </b>"+english+"<b> british: </b>"+british); //Set output element html
}
And it outputs this correctly but my questions is how would put this data into the below.
$scope.items = [
{
english: '<First Row english>',
british: '<First Row british>',
image: '<First Row icon>'
},
{
english: '<Second Row english>',
british: '<Second Row british>',
image: '<Second Row icon>'
}
//So on and so forth for all the records in the DB.
]
This is from api.php not sure if this needs to be returned a certain way?
<?php
require_once 'db.php'; // The mysql database connection script
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$query=mysql_query("SELECT * FROM $tableName") or die(mysql_error());
while($obj = mysql_fetch_object($query)) {
$arr[] = $obj;
}
echo $json_response = json_encode($arr);
?>
<?php
require_once 'db.php'; // The mysql database connection script
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$query=mysql_query("SELECT * FROM $tableName") or die(mysql_error());
$arr[];
while($obj = mysql_fetch_object($query)) {
array_push($arr, $obj);
}
echo $json_response = json_encode($arr);
?>
JS
$http.get('api.php').success(function(data) {
$scope.items = data;
});

Populating amchart dynamically fetching data from mysql

I am trying to fetch records from mysql and render the data via amchart, but I am facing difficulty in doing so. I have written the following code which is not working. The query works fine but the problem is replacing the static (placeholder) data with the results of the query. Please suggest.
{
$selectdata="SELECT member_lhp, COUNT( * ) AS 'land_pattern' FROM hh_basic_info GROUP BY member_lhp";
$resdata=mysql_query($selectdata);
<script type="text/javascript">
var chart;
var chartData = [
<?php
$count=0;
while($rowdata = mysql_fetch_assoc($resdata))
foreach($rowdata as $rows){
$type= $rows['member_lhp'];
$lp=$rows['land_pattern'];
if($count++ > 0) echo ',';
?>
{
year: <?php echo $type;?>,
income: <?php echo $lp;?>
},
<?php } ?>
];
AmCharts.ready(function () {
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "year";
// this single line makes the chart a bar chart,
// try to set it to false - your bars will turn to columns
chart.rotate = true;
// the following two lines makes chart 3D
chart.depth3D = 20;
chart.angle = 30;
// AXES
// Category
var categoryAxis = chart.categoryAxis;
categoryAxis.gridPosition = "start";
categoryAxis.axisColor = "#DADADA";
categoryAxis.fillAlpha = 1;
categoryAxis.gridAlpha = 0;
categoryAxis.fillColor = "#FAFAFA";
// value
var valueAxis = new AmCharts.ValueAxis();
valueAxis.axisColor = "#DADADA";
valueAxis.title = "Villagers - Land holding pattern";
valueAxis.gridAlpha = 0.1;
chart.addValueAxis(valueAxis);
// GRAPH
var graph = new AmCharts.AmGraph();
graph.title = "Income";
graph.valueField = "income";
graph.type = "column";
graph.balloonText = "Land holding number in [[category]]:[[value]]";
graph.lineAlpha = 0;
graph.fillColors = "#bf1c25";
graph.fillAlphas = 1;
chart.addGraph(graph);
// WRITE
chart.write("chartdiv");
});
</script>
}
At a quick glance it looks like you may have included an extra comma after your curly bracket. You are already adding a comma via the PHP if your count is greater than 0 so this would have been introducing a second, unnecessary one between each group of data.
You had the following...
{
year: <?php echo $type;?>,
income: <?php echo $lp;?>
},
try just having this instead...
{
year: <?php echo $type;?>,
income: <?php echo $lp;?>
}
It seems you forgot to parse in json format,
Just write
var newchartData= JSON.parse(chartData);
now assign newcharData to DataProvider,it should work.