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>
Related
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>
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"]));
I have been struggling with adding
google chart with my own mysql data to my wordpress page.
When I use this code in a simple html form. It works just fine:
http://fiber.web.tuke.sk/mon/x.php
When I use in in wordpress - I never get that working!!
Here is my code:
<?php
$con = mysqli_connect('100.100.25.100','user','Pass123#','pi2w_station');
?>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'Visits'],
<?php
$query = "select TimeStamp,temp_bmp180 from pi2w_attributes order by TimeStamp DESC LIMIT 100";
$exec = mysqli_query($con,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".$row['TimeStamp']."',".$row['temp_bmp180']."],";
}
?>
]);
var options = {
title: 'Date wise visits'
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
//var chart = new google.visualization.ColumnChart(document.getElementById("columnchart"));
//<div id="columnchart" style="width: 900px; height: 500px;"></div>
chart.draw(data, options);
}
</script>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
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;
});
I am new to this Google charting. I know this question has been asked many times. But all those quiet doesn't seem to solve my problem. So I am posting a fresh one of what my try has been so far.
<?php
$dbhost="localhost";
$dblogin="root";
$dbpwd="";
$dbname="myDB";
$db = mysql_connect($dbhost,$dblogin,$dbpwd);
mysql_select_db($dbname);
$day = date('d');
$month = date('m');
$lastMonth = (string)($month-1);
$lastMonth = strlen($month - 1) == 1? '0'.$lastMonth : $lastMonth;
$SQLString = "SELECT
count(analytics.day) as counts,
analytics.day, month,
date FROM analytics
WHERE year = '2012' AND month = '$month'
OR (month = '$lastMonth' and day > '$day')
GROUP BY day, month
ORDER BY date asc";
$result = mysql_query($SQLString);
$num = mysql_num_rows($result);
# set heading
$data[0] = array('day','counts');
for ($i=1; $i<($num+1); $i++)
{
$data[$i] = array(substr(mysql_result($result, $i-1, "date"), 5, 5),
(int) mysql_result($result, $i-1, "counts"));
}
echo json_encode($data);
mysql_close($db);
?>
Here is the database:
Database
Here is my .html file
<html>
<head>
<title></title>
<!-- Load jQuery -->
<script language="javascript" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js">
</script>
<!-- Load Google JSAPI -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "php/tracker.php",
dataType: "json",
async: false
}).responseText;
var obj = jQuery.parseJSON(jsonData);
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'yet to be decided'
};
var chart = new google.visualization.LineChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;">
</div>
</body>
</html>