I've successfully managed to create a line chart by retrieving the dataset from an ajax call when the line chart only has a single line.
I now need to create a line chart with 2 lines, but I can't get it working.
My ajax return data is built in php. This is the code:
$returnData['line'] = array(
'type' => 'line',
'title' => 'Title',
'labels' => array('Jan','Feb'),
'datasets' => array(
array(
'data' => array(0,50),
'borderColor' => "#f7464a",
'label' => "Label 1",
'fill' => false
),
array(
'data' => array(10,20),
'borderColor' => "#8e5ea2",
'label' => "Label 2",
'fill' => true
)
)
);
echo json_encode($returnData);
My jQuery ajax call is:
$.ajax({
url: "https://example.com/chart_data",
type: "POST",
dataType: 'json',
success: function(rtnData) {
$.each(rtnData, function(dataType, data) {
console.log(data.datasets);
var ctx = document.getElementById("linechart").getContext("2d");
var config = {
type: data.type,
data: {
datasets: [data.datasets],
labels: data.labels
},
options: {
responsive: true,
title: {
display: true,
text: data.title
}
}
};
window.myPie = new Chart(ctx, config);
});
},
error: function(rtnData) {
alert('error' + rtnData);
}
});
The data looks good when I view what has been logged in the console, so I don't know why this isn't working.
All I get is the chart, but no lines.
I'm looking for a future-proofed solution where I can add as many lines as needed to the chart just by amending the php code, without then having to change the jQuery too.
I've spotted my mistake in case anybody else runs into this....the square brackets need to be removed from the 'datasets' parameter:
$.ajax({
url: "https://example.com/chart_data",
type: "POST",
dataType: 'json',
success: function(rtnData) {
$.each(rtnData, function(dataType, data) {
console.log(data.datasets);
var ctx = document.getElementById("linechart").getContext("2d");
var config = {
type: data.type,
data: {
datasets: data.datasets,
labels: data.labels
},
options: {
responsive: true,
title: {
display: true,
text: data.title
}
}
};
window.myPie = new Chart(ctx, config);
});
},
error: function(rtnData) {
alert('error' + rtnData);
}
});
Related
I made a dynamic highstock (highchart) like this example, but with data from PHP. I have tried my code, but the results did not appear. How to make dynamic highstock with PHP?
PHP code :
<?php
include("connection.php");
$data = array();
$count = 0;
$result = mysqli_query($koneksi,"SELECT * FROM data ORDER BY time ASC ") or die ("Connection error");
while($row = mysqli_fetch_array($result)) {
$x = strtotime($row['time']) * 1000;
$y = (float)$row['temperature'];
$data[] = array($x, $y);
$count++;
}
echo json_encode($data);
mysqli_close($koneksi);
?>
JSON from PHP:
[[1535981121000,40],[1535981432000,32.9],[1535981492000,32.7],[1535981552000,32.6],[1535981618000,32.6],[1535981672000,32.6],[1535981732000,32.6],[1535981793000,32.6],[1535981854000,32.6],[1535981913000,32.5],[1535981993000,32.4],[1535982034000,32.4],[1535982215000,32.4],[1535982287000,32.3],[1535982335000,32.3],[1535982396000,32.5],[1536576266000,45.2],[1536579542000,62.2],[1536653234000,30.2]]
Javascript code:
<script type="text/javascript">
var chart;
function requestData() {
$.ajax({
url: 'chartTemp.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20;
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
document.addEventListener('DOMContentLoaded', function() {
chart = Highcharts.stockChart('container', {
chart: {
events: {
load: requestData
}
},
time: {
useUTC: false
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: true,
selected: 0
},
title: {
text: 'Live random data'
},
exporting: {
enabled: true
},
series: [{
name: 'Random data',
data: data[]
}]
});
</script>
I changed the javascript code above from this example
You are missing either,
// Set the JSON header (in .php)
header("Content-type: text/json");
Or like,
$.ajax({
method: "GET",
url: "test.js",
dataType: "json"
});
Also you have some syntax errors, at the end of javascript code add below (to confirm check in browser's console window),
)};
Your ajax call is returning all of the points in a single json, but the function you are calling looks like don't accept, so check again,
// add the point
chart.series[0].addPoint(point, true, shift);
I'm using C3 chart to present some data on my project and I want to show up legends (Label in my case) instead of numbers in the AcisX :
Data json format :
[
{"Label":"DQUA","Aut":3.75,"NoAut":3.75,"CM":32},
{"Label":"DPRO","Aut":43.9,"NoAut":0,"CM":144},
{"Label":"DMAI","Aut":1.6999999999999993,"NoAut":0,"CM":0},
{"Label":"DENG","Aut":0,"NoAut":0,"CM":16}
]
My attempt to get the task work :
var chart = c3.generate({
bindto: '.ks-chart-orders-block',
data: {
url: '/Home/AbsencesByDepartementFiltredByReasons',
mimeType: 'json',
type:'bar',
keys:{
value: ['Aut','NoAut','CM']
},
}
}
});
Getted Result :
Expected Result:
You need to modify the x-axis with a custom category:
var chart = c3.generate({
bindto: '.ks-chart-orders-block',
data: {
url: '/Home/AbsencesByDepartementFiltredByReasons',
mimeType: 'json',
type:'bar',
keys:{
x: 'Label',
value: ['Aut','NoAut','CM']
},
},
axis: {
x: {
type: 'category',
tick: {
centered: true
}
}
}
});
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'm trying to replace the highcharts that I loaded using ajax. Apparently what I am doing is that I would get new values from the user, send the new values thru Ajax, then return an entirely new graph(different graph type with different data) so what I'm doing is this:
$.ajax({
type: "POST",
url: $("#searchForm").attr( 'action' ),
data: $("#searchForm").serialize(),
success: function(response) {
$('#container').highcharts({ response });
}
});
But what happens is that it just loads a blank graph.
this is my highcharts code:
chart: { type: 'bubble', zoomType: 'xy'}, title: { text: 'Day at a Glance' }, tooltip: {}, xAxis:
{categories:[ 'Delta Air Lines' ]}, yAxis: { title: { text: '# of Crew' } }, series: [{name: '# of
Passengers', URLs:[ '#'], data: [['1',1,0]], point: { events: {click: function() { var someURL =
this.series.userOptions.URLs[this.x]; if (someURL) window.open('http://'+someURL); }}} }]
Is there something wrong with the way I call my ajax or there is something wrong with my highcharts code?
In the response you need to get json, like
{
chart:{
//any options
},
series: [{
data:[1,2,3] //any points
}]
}
So you cannot use something like highcharts({ response }) but highcharts(response)
I am working on the highchart.I came across a problem where the categories data and series data which I am loading dynamically is not showing up. Here is my code.
function loadChart() {
var categories = [];
var trend_series = [];
$.ajax({
type:'POST',
url : '/trends.php',
dataType: 'json',
async : 'false',
data: { date: d, item_name: item },
success: function( data ) {
$.each( data, function( key, val ) {
categories.push( key );
trend_series.push( parseFloat( val ) );
});
},
error: function( data ) {
//alert(data['responseText']);
}
});
$( function () {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line'
},
xAxis: {
categories: {}
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
});
chart.xAxis[0].setCategories( categories );
chart.addSeries({
name: 'App Summary',
data: trend_series
});
});
}
I am calling the loadChart() from another file.
One of the main problem which I notice that the categories and trend_series (these are arrays )is empty inside the highchart function . But it is not empty inside the ajax function call. How can I pass those values to highchart function or is there any other method to achieve this.
You're modifying the categories and the data but the chart has no way to be notified of that.
You need to do categories.push() and then redo chart.xAxis[0].setCategories(categories,true) again, and same with the data, chart.series[0].setData(trend_series,true) in your success function in the ajax call.
The true option triggers the chart.redraw()
I end up with this solution even though it is bit wierd,
I moved the enitre highchart function to another function. On ajax success function I am calling the next function renderChart() . The code is as follows.
function loadChart() {
categories = [];
trend_series = [];
$.ajax({
type:'POST',
url : '/trends.php',
dataType: 'json',
async : 'false',
data: { date: d, item_name: item },
success: function( data ) {
$.each( data, function( key, val ) {
categories.push( key );
trend_series.push( parseFloat( val ) );
});
renderChart(categories,trend_series);
},
error: function( data ) {
//alert(data['responseText']);
}
});
}
To load highchart
function renderChart(categories,trend_series){
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line'
},
xAxis: {
categories: {}
},
series: {}
}]
});
chart.xAxis[0].setCategories( categories );
chart.addSeries({
name: 'App Summary',
data: trend_series
});
}
Will be better if you use
$.ajax({
type:'POST',
url : '/trends.php',
dataType: 'json',
async : 'false',
data: { date: d, item_name: item },
success: function( data ) {
var options = {
chart: {
renderTo: 'container',
type: 'line'
},
xAxis: {
categories: []
},
series:{
data:[]
}
}
$.each( data, function( key, val ) {
options.xAxis.categories.push(key);
options.series.data.push( parseFloat( val ) );
});
var chart = new Highcharts.Chart(options);
},
error: function( data ) {
//alert(data['responseText']);
}
});