HighCharts and PHP json_encode. Data from MySQL. No data on chart - javascript

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

Related

Dynamic Chart in PHP using Chart js

I am not being able to show the values from my PHP file into my HTML file using Chart js. I am trying to import it through AJAX request. I tried it through printing the database value as JSON in the PHP file. The encoding worked well but I can't show them in graph for some reason. Please suggest any other way if possible to do the task mentioned in the code
HTML:
<html>
<head>
<meta charset="utf-8"/>
<title>Chart.js demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js" type="text/javascript"></script>
<script src="assets/js/jquery.min.js" type="text/javascript"></script>
<script src="assets/js/LineGraph.js" type="text/javascript" ></script>
</head>
<body>
<h1>Chart.js Sample</h1>
<div id= "graphDiv" style="width:100%; height:auto;">
</div>
<script>
showGraph();
function showGraph(){
$.post("agSensorInterfaceUpdate.php", function (data){
console.log(data);
var ctx = $("#graphCanvas");
var acc_data = [];
var gyr_data = [];
var serial = [];
for(var i in data) {
acc_data.push(data[i].accelerometer);
gyr_data.push(data[i].gyroscope);
serial.push(data[i].serial_no);
}
var chartdata = {
labels: serial_no,
datasets: [
{
label: 'Accelerometer Data',
backgroundColor: 'rgba(200,200,0.75)',
borderColor: 'rgba(200,200,0.75)',
hoverBackgroundColor: 'rgba(200,200,200,1)',
hoverBorderColor: 'rgba(200,200,200,1)',
data: acc_data
}
]
};
var lineGraph = new Chart(ctx, {
type:'line',
data: chartdata
});
});
}
</script>
</body>
PHP:
<?php
header('Content-Type: application/json');
$username = "root";
$password = "";
$database = "arthor_bb";
$serial=1;
$sensor_value = array();
$mysqli = new mysqli("localhost", $username, $password, $database);
$query = "SELECT * FROM `sensor_data`";
$result = $mysqli->query($query);
foreach ($result as $row){
$sensor_value[] = $row;
}
$result -> close();
print json_encode($sensor_value);
?>
your "graphDiv" html element needs to be a canvas. not a div.
<canvas id="myChart" width="100%" height="50%"></canvas>
You also have the wrong id on your ctx variable.
let ctx = document.getElementById('myChart').getContext('2d'); // canvas

How do I create a C3 Chart Line Graph from JSON data?

I need help for a school project. I have been able to pull data from a mySQL database into an array and encoded into JSON, which displays fine. Now, I need help with passing the JSON data to C3 to produce a chart (if possible on the same page).
What I've done so far:
$strQuery = "SELECT production_date,oil FROM production WHERE well = '$h_well' AND production_date BETWEEN '$h_start' AND '$h_end' ORDER BY production_date ASC";
$result = mysqli_query($conn, $strQuery);
// Print out rows
$data = array();
while ( $row = $result->fetch_assoc() ) {
$data[] = $row;
}
echo json_encode( $data );
You need to create two separate array, one for your data and one for dates that you want to show on x-axis and then pass that array to java script.
here is full working example
<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$strQuery = "SELECT production_date,oil FROM production WHERE well = '$h_well' AND production_date BETWEEN '$h_start' AND '$h_end' ORDER BY production_date ASC";
$result = mysqli_query($conn, $strQuery);
// Print out rows
$valuesArray = array();
$datesArray = array();
$valuesArray[] = 'Oil';
$datesArray[] = 'x';
while ($row = $result->fetch_assoc()) {
$datesArray[] = $row['production_date'];
$valuesArray[] = $row['oil'];
}
?>
<html>
<head>
<title>C3 Liner example</title>
<link href="c3_scr/c3.css" rel="stylesheet" type="text/css" />
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="c3_scr/c3.js"></script><!-- load jquery -->
</head>
<body>
<div id="chart"></div>
<script>
var xAxisArr = <?php echo json_encode($datesArray); ?>;
var dataArr = <?php echo json_encode($valuesArray, JSON_NUMERIC_CHECK); ?>;
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'x',
columns: [
xAxisArr,
dataArr
]
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d'
}
}
}
});
</script>
</body>
</html>

Loading data to Highchart from MySQL and displaying in appropriate way

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/

CanvasJs dynamic Data with PHP, mySQL

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.

Making a graph in php, mysql with highcharts

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.

Categories

Resources