I am facing the problem with highchart. I've been looking for solution for 2 days without result.
live-data.php
<?php
header("Content-type: text/json");
include("./dbSettings.php");
$result = $conn->query("SELECT current_ts, heartRate FROM data WHERE id='1234'");
if (!$result) {
die(mysqli_error($conn));
}
$ret = array();
while ($row = mysqli_fetch_array($result)){
$current_time = strtotime($row['current_ts'])*1000;
$heartRate = intval($row['heartRate']);
$y = rand(0, 100);
$ret[] = array($current_time, $heartRate);
}
echo json_encode($ret, JSON_NUMERIC_CHECK);
?>
output from live-data.php
[[1463404815000,131],[1463404926000,108],[1463404927000,180],[1463404928000,160],[1463404967000,143],[1463404968000,105],[1463404969000,107],[1463404976000,100],[1463404977000,123],[1463867458000,108],[1463867459000,113],[1463867460000,108],[1463867494000,97],[1463867495000,158],[1463867496000,74]]
index.html (it's totally wrong, but I attach it)
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#*" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script data-require="highcharts#*" data-semver="4.0.1" src="//cdnjs.cloudflare.com/ajax/libs/highcharts/4.0.1/highcharts.js"></script>
<link rel="stylesheet" href="style.css" />
<script>
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: [{}]
};
$.getJSON('live-data.php', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
I would like to make my chart looking like this one below, but a bit more detailed. I will retrieve data from my database every minute. Chart will be updated after manually refresh, but in the future I will make it dynamically (using ajax). It will be great if I could show data in appropriate way (i.e. April 7, 2016, 15:12:38)
http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/stock/demo/basic-line/
I hope someone can help me on my way.
Thanks,
Paul
I've assumed you are talking about tooltip dates because on Axis your label will be too long.
You need to play with dateTimeLabelFormats. See my example:
http://jsfiddle.net/qq5rqazj/2/
Related
I am using google charts to display a line graph on my locally hosted web page. I am using mysqli to take the data from my phpmyadmin database then echoing this into the row spaces in the javascript.
This is the code within my html body:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<script>
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Speed');
data.addRows([
<?php
$sql = "SELECT id_rides, speed, date_completed FROM rides_done WHERE (id_users = $_SESSION[id])";
$result = mysqli_query($link, $sql);
while($row = mysqli_fetch_assoc($result)) {
$date = $row['date_completed'];
$speed = floatval($row['speed']);
echo "['".$date."', ".$speed."],";
}
?>
]);
var options = {
hAxis: {
title: 'Ride date'
},
vAxis: {
title: 'Average speed'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
The problem is that nothing is being displayed on the web page.
I know that the query works as I tried this on it's own outside of the javascript and this was output: results of sql query
Before I added the dynamic element of the chart it was working fine with just random lists of data.
I was expecting to see a line graph with 'Average Speed' on the y-axis and 'Ride date' on the x-axis with 7 datapoints but nothing was displayed.
It seems that js is particular about datatypes here so I'm wondering if it is something to do with either of the following lines - both of which I have been fiddling around with to no avail.
echo "['".$date."', ".$speed."],";
data.addColumn('string', 'Date');
data.addColumn('number', 'Speed');
Thank you very much. All suggestions and ideas are very welcome. As is probably evident I am very new to Javascript so likely to be making some stupid mistakes.
A couple of things I would say: As you appear to wish to use a date within the dataTable perhaps setting that as a date type column would be better and casting the value from the db query as a date using new Date(str). I'd also suggest that you use json_encode once you have run the db query to create a JSON object rather than manually building a string as you do above - one downside to that approach is the trailing comma which might cause issues.
I rattle together a working demo using bogus data from my db to emulate what you were trying to do here. The SQL query uses aliases to take arbitrary data and name it as you do so the Javascript remains fairly much the same.
With the JSON data it is easy to iterate through the Object using Object.keys( json ).forEach() type structure ( I apologise if this is new to you )
<?php
#add a db connection
chdir('../../dbo');
require 'db-conn-details.php';
require 'mysqli-conn.php';
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script src='//www.gstatic.com/charts/loader.js'></script>
<script></script>
<title>Google charts.....</title>
<style>
#chart_div{
width:800px;height:600px
}
</style>
</head>
<body>
<div id='chart_div'></div>
<script>
<?php
$sql = 'SELECT `speed`, `date_completed` FROM `rides_done` WHERE ( `id_users` = $_SESSION[id] )';
$sql = 'select `dr` as `speed`, date(`lasteditdate`) as `date_completed` from `testtable` limit 20'; # example sql...
$result = $link->query( $sql );
$json = json_encode( $result->fetch_all( MYSQLI_ASSOC ) );
printf('const json=%s;', $json );
?>
google.charts.load('current', { packages: ['corechart'] } );
google.charts.setOnLoadCallback( drawBasic );
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Speed');
Object.keys( json ).forEach( key=>{
let obj=json[ key ];
data.addRow( [ new Date( obj.date_completed ), parseFloat( obj.speed ) ] );
})
var options = {
hAxis: {
title: 'Ride date'
},
vAxis: {
title: 'Average speed'
}
};
var chart = new google.visualization.LineChart( document.getElementById('chart_div') );
chart.draw( data, options );
}
</script>
</body>
</html>
The above yielded a chart like this:
i want to create google pie chart with help of getting table from database ...but till now i did not get output ...i have searched several websites..but i did not clarify anything...please check my code and tell
<?php
mysql_connect('localhost','root','');
mysql_select_db('chart');
$sqlquery1="select * from pie_chart";
$sqlresult1=mysql_query($sqlquery1);
$rows=array();
while($r=mysql_fetch_assoc($sqlresult1))
{
$rows[]=$r;
}
$data= json_encode($rows);
?>
<html>
<head>
<!--Load the AJAX API -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
//Load the visualization API and the piechart package
google.load('visualization','1',{'packages':['corechart']});
//Set a callback to run when the google visualization API is loaded
google.setOnLoadCallback(drawchart);
function drawChart(){
var data = new google.visualization.DataTable();
data.addColumn("string", "Quarter");
data.addColumn("number", "Number");
data.addRows(<?php echo $data ?>);
]);
//Create our data table out of JSON data loaded from server
var data=new google.visualization.DataTable(jsonData);
//Instantiate and draw our chart, passing in some options
var chart=new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data,{width:400,height:240});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart -->
<div id="chart_div"></div>
</body>
</html>
<?php
/* Establish the database connection */
$mysql =mysqli_connect('localhost', 'root', '', 'chart');
/* select all the tasks from the table piechart */
$result = $mysql->query('SELECT * FROM piechart');
/*
---------------------------
example data: Table (piechart)
--------------------------
Task percent
job 30
daily 20
working 35
sleep 15
*/
$rows = array();
$table = array();
$table['cols'] = array(
// Labels for your chart, these represent the column titles.
/*
note that one column is in "string" format and another one is in "number" format
as pie chart only required "numbers" for calculating percentage
and string will be used for Slice title
*/
array('label' => 'task', 'type' => 'string'),
array('label' => 'percent', 'type' => 'number')
);
/* Extract the information from $result */
/* associate array are used in above ,so we used foreach loop*/
foreach($result as $r)
{
$temp = array();
// The following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['task']);
// Values of the each slice
$temp[] = array('v' => (int) $r['percent']);
//rows of side title
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
// convert data into JSON format
$jsonTable = json_encode($table);
//echo $jsonTable;
?>
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Load the Visualization API and the piechart package.
function drawChart()
{
// Create our data table out of JSON data loaded from server.
var bar_chart_data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
var options = {
title: 'Daily Work log',
is3D: 'true',//3D effect true
width: 900,
height: 500
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(bar_chart_data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="chart_div" ></div>
</body>
</html>
</script>
</head>
Trying to produce HighCharts with data from MySQL. Parsing data from MySQL using PHP and the json_encode function. Problem: No data on chart.
This is my javascript:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<style type="text/css">
</style>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: [{}]
};
$.getJSON('json.php', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
</script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<div id="container" style="max-width: 500px; height: 400px; margin: 0 auto"></div>
</body>
</html>
This is my json.php:
<?php
$host = "localhost:3306";
$user = "removed";
$pass = "removed";
$dbname = "removed";
$connection = mysqli_connect($host, $user, $pass, $dbname);
$query = "SELECT temp, time from vejr where time > '2016-04-25 06:14:23'";
$result = mysqli_query($connection, $query);
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
?>
This is the output from the json.php:
[{"temp":"1.6","time":"2016-04-25 08:14:23"}, {"temp":"2.6","time":"2016-04-25 09:14:23"},{"temp":"3.6","time":"2016-04-25 10:14:23"},{"temp":"4.6","time":"2016-04-25 11:14:23"}, {"temp":"5.6","time":"2016-04-25 12:14:23"},{"temp":"6.6","time":"2016-04-25 13:14:23"},{"temp":"7.6","time":"2016-04-25 14:14:23"},{"temp":"8.6","time":"2016-04-25 15:14:23"}]
What I'm trying to do is a chart with time (fx 2016-04-25 08:14:23) on the x-axis, and the value (fx 1.6) on the y-axis.
Got inspiration from this: http://www.highcharts.com/docs/working-with-data/custom-preprocessing#3
And also, I know that my timestamp on the x-axis is not perfect, it is long (2016-04-25 08:14:23), but that is what my feeding-software currently is sending to my MySQL. What would be perfect?
Kind Regards
The issue is caused by 3 reasons.
Values should be named like x and y, not custom fields
The y value should be number, not string like you have (use the JSON_NUMERIC_CHECK flag in json_encode)
The x value, should be timestamp (time in miliseconds). In PHP you can use strtotime() function
screen shoot
Hello i have obstacle for my chart from CanvasJs.
I just put simple code to get simple chart with parameter target and actual, i found error in dataPoints: i think the problem just wrong statements.
this my error code:
dataPoints: [
<?PHP $mkmi3= mysql_query("SELECT * FROM monthkpimontindv WHERE idKpiDetIndv='$q'");
While ($mkmi4= mysql_fetch_assoc($mkmi3))
{
echo "{ label: ".$mkmi4['period'].", y: ".$mkmi4['actual']." },\n";
}
?>
]
Here is how we can display MySQL data in CanvasJS, Try like this.
Here, Create a PHP service that returns data in JSON format. HTML page that does AJAX request to the server and fetches the data. After getting the data, it renders a Chart.
PHP Service to return JSON Data
<?php
header('Content-Type: application/json');
$con = mysqli_connect("127.0.0.1","user","password","canvasjssampledb");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}else
{
$data_points = array();
$result = mysqli_query($con, "SELECT * FROM sales");
while($row = mysqli_fetch_array($result))
{
$point = array("label" => $row['product'] , "y" => $row['total_sales']);
array_push($data_points, $point);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
}
mysqli_close($con);
?>
HTML Page to Fetch Data and render Chart
!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script src="jquery.js"></script>
<script src="canvasjs.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("data.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: result
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 380px;"></div>
</body>
</html>
Note:: IE8- is supported in v1.3 and above.
I need make a graph in highcharts, but I need to get the values from mysql until now I only can add the timestamp value, but still left the other value to the Y graph, Im new in all this I hope you can give some help, the other value I need to use is a int value.
I'm still trying to add the second value, but with this only value (hour) shows me nothing.
The homework is to make a graph with values in function of time
<HTML>
<head>
<!-- Importa las librerias de jQuery y las de Highcharts -->
<script type="text/javascript" src="https://code.jquery.com/jquery.js"></script>
<script type="text/javascript" src="http://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript" src="http://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<?php
$conexion = mysql_connect('localhost','root' , '') or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db('fancysensorsdb', $conexion);
$query = "SELECT hora FROM temperatura";
$registros = mysql_query($query) or die(mysql_error());
while ($datos = mysql_fetch_array($registros))
{
extract ($datos);
$datetime *= 1000; // Convertir hora Unix a JavaScript
$data[] = "[$datetime, $hora]";
}
$query = "SELECT valor FROM temperatura";
$registros = mysql_query($query) or die(mysql_error());
while ($valores = mysql_fetch_array($registros))
{
extract ($valores);
$datos[] = $valores;
}
?>
<script type="text/javascript">
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container'
},
series: [{
data: [<?php echo join($data, ',') ?>]
}]
});
</script>
<div id="container" style="width: 100%; height: 500px; margin: 0 auto"></div>
</body>
</html>
Basically you are passing variable data from PHP to javaScript. Based on your code, it won't work. Please take a look at this post.