I am working with Highchart. I want to draw dynamic graph with database value. I use json format.
Here is my json file:
<?php
// Set the JSON header
header("Content-type: text/json");
include"../veri_ayar.php";
$sql = "SELECT Guc FROM Urun ORDER BY KayitTarihi DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
$data = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
$x = time() * 1000;
foreach($data as $dat)
{
$date .= $dat['Guc'];
}
mysqli_close($conn);
$ret=array($x, $date);
echo json_encode($ret);
?>
And my output is : [1479814215000,"43"]
When I write to just $date for control it looks like: just 43 but when I write to json format it looks like "43".
When I want to draw graph my graph is shift left but no data in graph. just shift to left.
Here is my graph script:
<script>
var chart;
function requestData() {
$.ajax({
url: 'veri-json.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
</script>
Related
I am Trying to make a HighChart's Line Chart Based on the data from the Database.
I Fetched the Data from The Database as I can see that data in the console .
The php Code I Used is :
<?php
$query = "
SELECT YEAR(created_at) AS year,
MONTHNAME(created_at) AS month,
COUNT(*) AS count
FROM users
GROUP BY month ASC ORDER BY created_at ASC
" ;
$result = mysqli_query($conn, $query) ;
while ($row = mysqli_fetch_assoc($result)) {
$data1[] = $row['month'];
$data2[] = $row['count'];
}
?>
Now I Fetched the Data in Highchart's script as Follows :
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
type: 'line',
},
title: {
text: 'Download Trends'
},
credits: {
enabled: false
},
xAxis: {
categories: ['<?php echo join($data1, "','"); ?>'],
},
yAxis: {
min: 0,
title: {
text: 'No. of Downloads'
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Qty',
data: ['<?php echo join($data2, "','"); ?>'],
}]
});
});
</script>
I using the container div with id container as follows :
<div id="container"></div>
The Problem is that the data is not showing in correct Manner . its been showing only half of the data as you can see below :
its not showing the Line.
Please Help
Your data serie is made of strings, and Highcharts works with numbers for this kind of graph.
Remove the simple quotes in the data section and it should works :
data: [<?php echo join($data2, ","); ?>]
I have a database with timestamp for three different parameters but for educational purposes only I am trying to do just one graph on one parameter in real time.
Here is my php code:
if ($result->num_rows > 0) {
$count =0;
echo '[';
while($row = $result->fetch_assoc()) {
echo '['.$row["time"].','.$row["temperature"].']';
$count++;
if ($count<"100") {
echo ',';
}
}
echo ']';
}
else {
echo "[[],[]]";
}
$link->close();
?>
The following php code displays:
[[1511533905000,34],[1511534125000,34],[1511534201000,34],[1511535161000,34],[1511535221000,34],[1511535281000,34],[1511535306000,34],[1511535606000,34],[1511535907000,34],[1511536207000,34],[1511536507000,34],[1511536807000,34],[1511537108000,34],[1511537408000,34],[1511537708000,34],[1511538070000,85],[1511538370000,31],[1511538670000,31],[1511538971000,30],[1511539271000,30],[1511539571000,30],[1511539872000,30],[1511540172000,30],[1511540472000,30],[1511540773000,30],[1511936414000,25],[1511936714000,24],[1511937014000,85],[1511937315000,24],[1511937616000,24],[1511937916000,24],[1511938216000,24],[1511938517000,24],[1511938817000,24],[1511939117000,24],[1511939417000,24],[1511939718000,24],[1511940018000,24],[1511950908000,85],[1511951208000,23],[1511951509000,23],[1511951809000,23],[1511952109000,23],[1511952410000,23],[1511952710000,22],[1511953010000,22],[1511953310000,22],[1511953611000,22],[1511953911000,22],[1511954211000,22],[1511954512000,22],[1511954812000,22],[1511955112000,22],[1511955412000,22],[1511955713000,22],[1512056186000,31],[1512056486000,85],[1512056787000,30],[1512057087000,31],[1512057387000,30],[1512057688000,30],[1512057988000,30],[1512058289000,30],[1512058589000,30],[1512058889000,30],[1512059189000,30],]
now here is the html code:
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
//defaultSeriesType: 'spline',
},
title: {
text: 'Live random data'
},
events:{
load: refreshChart()
},
xAxis: {
type: 'datetime',
},
tooltip: {
valueSuffix: ' C'
},
yAxis: {
type: 'linear',
title: {
text: 'Temperature ( C)'
},
},
series: [{}]
});
$.getJSON("index.php", function(json) { /*Get the array data in data.php using jquery getJSON function*/
options.series[0].data = json; /*assign the array variable to chart data object*/
chart = new Highcharts.Chart(options); /*create a new chart*/
});
function refreshChart(){ /*function is called every set interval to refresh(recreate the chart) with the new data from data.php*/
setInterval(function(){
$.getJSON("index.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.Chart(options);
});
},6000);
}
});
But the graph doesnt display anything? Anyhelp pls?
SOLVED!! I just converted the output of my array in the index.php.
$output[] = array(((float)($row["time"])),((int)($row["temperature"])));
in this way both the timestamp and the value of the temperature are both valid json.
hi everyone im working on real-time java script chart to display data from a database but all i get is nothing its not catching data from data base
i used this php code
<?php
header("Content-type: text/json");
$servername = "localhost";
$username = "root";
$password = "";
$value = $_GET['value'];
$date = time() * 1000;
$ret = array($date, $value);
echo json_encode($ret);
$conn = mysql_connect($servername, $username, $password);
if ($conn) {
echo "Connected successfully";
}
else {
echo "connection failed";
}
$conndb = mysql_select_db('database', $conn);
echo "<br>";
$sql_insert ="insert into pulsesensor(value) values ('$value')";
if($sql_insert){
echo "insert successfull";
}
else {
echo "insert failed";
} echo "<br>";
$result = mysql_query($sql_insert);
if($result){
echo "insert successfull";
}
else {
echo "insert failed" . mysql_error($result);
}
?>
and for real-time chart i used this code
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0
auto">
</div>
/**
* Request data from the server, add it to the graph and set a timeout
* to request again
*/
function requestData() {
$.ajax({
url: 'mysql0.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live Heartbeats data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'heartbeats data',
data: []
}]
});
});
</script>
at the end the result is this
I'm trying to plot data from a mysql table on document load with highcharts:
the html looks like that:
function FetchData(){
//alert("Fetching");
$.ajax({
url: 'php/reports/fetch_data.php',
success: function(data) {
dataTemp = [];
for(i=0;i<data.length;i++){
dataTemp.push(data[i][0]); // '1' index for getting that temp value. '0' for date.
}
c_temperature.series[0].data = dataTemp;
for(i=0;i<data.length;i++){
dataTemp.push(data[i][1]); // '1' index for getting that temp value. '0' for date.
}
c_temperature.series[1].data = dataTemp;
}
});
function DrawCharts(){
c_temperature = new Highcharts.Chart({
chart: {
renderTo: 'dashboard',
defaultSeriesType: 'spline',
},
title: {
text: 'Temperatur'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 10
}
},
legend:{
enabled: false
},
credits:{
enabled: false
},
series: [{
name: 'Temperatur',
data: []
}]
});
$(document).ready(function() {
DrawCharts();
FetchDevices();
FetchData();
});
<body>
<div id="dashboard">
</div>
<div class="clear"></div>
</body>
And the php I call looks like that:
try {
$con = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);#
echo 'Connected</br>';
$sql = "select ZEIT,FEUCHTE,TEMPERATUR,LUX,PITCH from ".$mac.
" order by ID";
foreach($con - > query($sql) as $row) {
$x = $row['ZEIT'];
/*$x = mktime()*1000;*/
$y_h = (float) $row['FEUCHTE'];
/*$y_t=(float)$row['TEMPERATUR'];
$y_l=(float)$row['LUX'];
$y_a=(float)$row['PITCH'];*/
$ret = array($x, $y_h, /*$y_t,$y_l,$y_a,$mac*/ );
echo json_encode($ret);
}
$con = null;
}
The php code successfully returns data.
But I dont see a graph and debugging with the browser console does not give a clue either. Any suggestions what I'm doing wrong?
Beste Regards
You want to use c_temperature.series[0].setData(dataTemp, true); and c_temperature.series[1].setData(dataTemp, true);. By setting the data, you're not actually telling highcharts to redraw the chart, so nothing is happening when you update the data.
I think it has to do with the order in wich you do your operations: firstly you create the chart and then you make the ajax call to fetch the data, but you are not updating the chart.
Try to move the chart creation inside the ajax success callback: first populate the series array with the data received from PHP, then construct the chart passing the serie array as a option; like this:
success: function(data) {
var data_series = [];
/* here populate the data_series array from your PHP results */
new Highcharts.Chart({
/* here other options... */
series: data_series
});
So this is what I'm doing now:
function FetchData(){
$.ajax({
type: "POST",
url: 'php/reports/fetch_data.php',
data: "",
dataType: 'json',
success: function(data) {
var points = data;
c_temperature = new Highcharts.Chart({
chart: {
renderTo: 'dashboard',
defaultSeriesType: 'spline',
},
title: {
text: 'Temperatur'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: '°C',
margin: 10
}
},
legend:{
enabled: false
},
credits:{
enabled: false
},
series: points
});
/*dataTemp = [];
for(i=0;i<data.length;i++){
dataTemp.push(data[0][i]);
}
c_temperature.series[0].setData(dataTemp, true);
for(i=0;i<data.length;i++){
dataTemp.push(data[1][i]);
}
c_temperature.series[1].setData(dataTemp, true);*/
}
});
}
Result: it is showing the graph but still no plot.
The php return has been changed to this:
try {
$con = new PDO("mysql:host=$servername; dbname=$dbname" ,$username, $password);
$sql = "select ZEIT,FEUCHTE,TEMPERATUR,LUX,PITCH from ".$mac." where ID>'60080' order by ID";
$x = array();
$y_h = array();
foreach ($con->query($sql) as $row)
{
$x[]=$row['ZEIT'];
$y_h[]=(float)$row['FEUCHTE'];
$ret = array($x,$y_h);
}
echo json_encode($ret);
$con = null;
}
I have been able to produce results from mysql using:
$myArray=array();
$tempArray = array();
// Get all records
while ( $row = $results->fetch_assoc())
{
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
$mysqli->close();
?>
And I then included this to produce a chart on my page index.php by using the following Javascript.
what concepts/code am I not understanding/missing to produce a chart based upon my ajax json?
EDITED - SOLUTION:
Final PHP code to produce the json:
while ( $row = $results->fetch_assoc())
{
$tempArray[0] = $row['unix_timestamp(auct.end_date)'];
$tempArray[0] *= 1000;
$tempArray[1] = $row['winning_bid'];
array_push($myArray, $tempArray);
}
echo json_encode ($myArray, JSON_NUMERIC_CHECK);
$mysqli->close();
?>
Final javascript code:
$('#btn_search').click(function(){
txt_search = $('#txt_search').val();
$.ajax({
url: './php/search.php',
type: 'GET',
data: {search: txt_search},
dataType: 'json',
success: function(rows)
{
chart = new Highcharts.Chart({
chart: {
renderTo: 'chartdiv',
type: 'line',
marginRight: 100,
marginBottom: 50
},
title: {
text: 'Whisky Tracking',
x: -20 //center
},
xAxis: {
text: 'EndDate',
type: 'datetime'
},
yAxis: {
title: {
text: 'Price',
color: '#CC680E'
},
plotLines: [{
value: 0,
width: 20,
color: '#CC680E'
}]
},
series: [{
name: txt_search,
xAxis:0,
data: rows,
dataLabels: {
enabled: true,
formatter: function() {
return '£'+ Highcharts.numberFormat(this.y, 0);
}
}
}],
});
}
});
goToByScroll('tracker');
return false;
});
Sample Data from the JSON:
[1306732000000,160],[1306745000000,45],[1306788000000,65],[1306788000000,50],[1306712000000,130],[1306733000000,240],[1306744000000,60],[1306788000000,250],[1306710000000,145]
The problem is that values are strings, for example, your data:
["2011-05-30 00:00:00","130"]
Should be instead:
[1306706400000, 130]
To it's timestamp in ms and true value.
You can read about JSON_NUMERIC_CHECK option for json_encode(string, JSON_NUMERIC_CHECK) to change strings to numbers. But dates to timestamps you need to change on your own.
Edit:
Also the problem was with setting data in doubled array, changed from:
data: [rows]
to:
data: rows