My target: I want to draw HighStock-chart with multiple series. Data is loaded by AJAX from data.php. The output of data.php is an JSON-Array
My problem: I don't know hot to grab the data from JSON Array
The output is e.g
[[timestamp,value1,value2],[timestamp,value1,value2]]
Series 1 should be -> timestamp and value1
Series 2 should be -> timestamp and value2
This is my code
// Draw the chart
$(function(){
/* The chart is drawn by getting the specific data from "data.php".
* The configuration settings are transmitted by GET-Method. The output is an JSON-Array. */
$.getJSON('data.php',
function(data) {
chart = new Highcharts.StockChart
({
chart: { renderTo: 'chartcontainer', type: 'line' },
title: { text: 'You see the data of the last hour!' },
xAxis: { type: 'datetime', title: { text: 'time' } },
yAxis: { title: { text: 'unit' } },
series: [{ name: 'series1', data: data },{ name: 'series2', data: data }],
});
});
});
I think i have to change
series: [{ name: 'series1', data: data },{ name: 'series2', data: data }],
But I dont know in to what
Iterate through all items of the data array, and populate two separate arrays:
var series1 = [];
var series2 = [];
for (var i = 0; i < data.length; i++) {
series1.push([data[0], data[1]);
series1.push([data[0], data[2]);
}
You then have the timestamp-value pairs in each of the series arrays.
Doing this in php might be more efficient, especially if you can replace the current json creation.
Related
i need help how to make php code for array data to chartjs, i use 2 table and i hope to generate array code like below
function revenueCost(year) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name=\'csrf-token\']').attr('content')
},
url: url,
data: {
year: $('#year').val(),
},
type: 'POST',
dataType: 'JSON',
success:function(data){
// console.log(data);
$('#revenue-cost').empty();
var myChart = new Chart(document.getElementById('revenue-cost'), {
type: 'bar',
data: {
labels: data.label,
datasets: [{
label: 'Revenue',
data: data.revenue,
borderWidth: 0.5,
borderColor: '#00642c',
backgroundColor: 'rgba(0,100,44,0.2)'
},{
label: 'Cost',
data: data.cost,
borderWidth: 0.5,
borderColor: '#a80e19',
backgroundColor: 'rgba(168,14,25,0.2)'
}]
},
options: {
scales: {
yAxes: [{
ticks: {beginAtZero: true}
}]
}
}
});
},
});
}
and i want to make array like this
{"label":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],"revenue":[105,85,55,68,72,8,0,0,0,0,0,0],"cost":[41,32,22,23,26,3,0,0,0,0,0,0]}
and chartjs view like this
chartjs grouping month
As I see the solution could be simple:
Send a POST HTTP request to your PHP file.
Validate you have a POST request with an if sentence and isset($_POST)
Prepare or extract the data, and create an associative array like the next one:
$label_data = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
$revenue_data = [105,85,55,68,72,8,0,0,0,0,0,0];
$cost_data = [41,32,22,23,26,3,0,0,0,0,0,0];
$data = [
'label' => $label_data,
'revenue' => $revenue_data,
'cost' => $cost_data
];
echo json_encode($data);
if you have data divided between arrays just merge them with array_merge and store the result in a new variable
$label_first = ["Jan","Feb","Mar","Apr","May","Jun"];
$label_second = ["Jul","Aug","Sep","Oct","Nov","Dec"];
$label_data = array_merge($label_first, $label_second );
Finally catch the response in your $.ajax and, perform the action you want to do the data.
I hope this information could be useful for you.
I tried to implement a chart with chart and ajax data type. When I would show result of a call in the xAxis not showing anything. This is a code of this chart
<div id="main" style="width:600px; height:400px;"></div>
<script type="text/javascript">
var myChart = echarts.init(document.getElementById('main'));
var dati = $.ajax({
url: '../../admin/root/chart.php', // provide correct url
type: 'POST',
dataType: 'JSON', // <-- since youre expecting JSON
success: function(chart_values) {
console.log(chart_values); // take a peek on the values (browser console)
}
});
// specify chart configuration item and data
option = {
legend: {},
tooltip: {},
dataset: {
// Provide data.
source: [
['product', 'Aperti', 'chiusi'],
['Cognome'],
]
}, // Declare X axis, which is a category axis, mapping
// to the first column by default.
xAxis : {
type: 'category',
data: dati
}, // Declare Y axis, which is a value axis.
yAxis: {}, // Declare several series, each of them mapped to a
// column of the dataset by default.
series: [
{type: 'bar'},
{type: 'bar'},
{type: 'bar'}
]
}
// use configuration item and data specified to show chart
myChart.setOption(option);
</script>
And this is what I call
$utente = mysqli_query($conne,"SELECT * FROM operatore") or die("Error:
".mysqli_error($conne));
while ($row=mysqli_fetch_array($utente)) {
$cognome=$row['cognome'];
$aperti=mysqli_query($conne,"SELECT * FROM rapportino WHERE
id_operatore='$row[matricola]'");
if ($aperti) {
$conta_ape=mysqli_num_rows($aperti);
}
$chiusi = mysqli_query($conne,"SELECT * FROM compila_rapportino WHERE
operatore_chius='$row[matricola]'");
if ($chiusi) {
$conta_chi=mysqli_num_rows($chiusi);
}
$myArray = array(
'cognome'=>$cognome,
'aperti' => $conta_ape,
'chiusi' => $conta_chi,
);
echo json_encode($myArray);
}
In this call data result can be repeat in different moment.
But from what I can see in your current post, you're dealing incorrectly with the Ajax call: you do the call, don't pass your data to the code that creates the chart. What you should do is to put this part of your code:
// specify chart configuration item and data
option = {
legend: {},
tooltip: {},
dataset: {
// Provide data.
source: [
['product', 'Aperti', 'chiusi'],
['Cognome'],
]
}, // Declare X axis, which is a category axis, mapping
// to the first column by default.
xAxis : {
type: 'category',
data: dati
}, // Declare Y axis, which is a value axis.
yAxis: {}, // Declare several series, each of them mapped to a
// column of the dataset by default.
series: [
{type: 'bar'},
{type: 'bar'},
{type: 'bar'}
]
}
// use configuration item and data specified to show chart
myChart.setOption(option);
inside the success callback and use the data that you get (chart_values):
var myChart = echarts.init(document.getElementById('main'));
var dati = $.ajax({
url: '../../admin/root/chart.php', // provide correct url
type: 'POST',
dataType: 'JSON',
success: function(chart_values) {
console.log(chart_values); // take a peek on the values (browser console)
//# put that code here and use chart_values!
}
});
This way, once you get the data, you'll be able to draw the chart.
I am trying to fetch data from MySQL database and display on a column chart using HIghChart but nothing seems to be showing.
This is my view:
<div id="last7days">
</div>
<script type="text/javascript">
$(function () {
//var data_click = 4;
//var data_viewer = 5;
Highcharts.chart('last7days', {
chart: {
type: 'column'
},
title: {
text: 'Last 7 days Transactions'
},
xAxis: {
categories: jdata.date, //['2013','2014','2015', '2016']
},
yAxis: {
title: {
text: 'Amount(in naira)'
}
},
series: [{
name: 'Credit',
data: jdata.credit
},{
name: 'Debit',
data: jdata.debit
}]
});
});
</script>
Find attached, here is the json data being returned by the controller
{"date":["2017-12-20","2017-12-21","2017-12-22"],"credit":["500600.00","2000.00","5600.00"],"debit":["0.00","0.00","47582.00"]}
Update:
I think its because the numbers in the array are in quotes, how do I remove the quotes?
I found the solution. Simply add JSON_NUMERIC_CHECK to your json_encode() function in the controller.
For example,
json_encode($result, JSON_NUMERIC_CHECK)
well, to start I used to make my JSON function, but when I wanted add data I couldn't. So How can I my json function ? i'm using getJSON but I can't add data like ajax then how could I change it to ajax style. it's for hightchart
$(function() {
var processed_json = new Array();
$.getJSON('../controllers/chart_controller.php', function(data){
for (i = 0; i < data.length; i++){
processed_json.push([data[i].key,data[i].value]);
}
//draw chart
$('#salesChart').highcharts({
chart: {
type: "column"
},
title: {
text: "Best selling product"
},
xAxis: {
type: 'category',
allowDecimals: false,
title: {
text: ""
}
},
yAxis: {
title: {
text: "Scores"
}
},
series: [{
name: 'Sales',
data: processed_json
}]
});
});
});
I'm trying to create a chart using data from my database calling json, but its not showing the results in the chart.
Here's my code so far:
$(document).ready(function() {
function requestData() {
$.ajax({
url: 'data.php',
datatype: 'json',
success: function(data) {
alert(data);
chart.series[0].setData(data[0]);
},
cache: false
});
}
var chart;
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
events: {
load: requestData
}
},
xAxis: {
},
yAxis: {
title: {
text: 'Value'
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
And here's my data.php code
$query = "SELECT tiempo,Fp1Ref
FROM GraficaEEG limit 10";
$data = mysqli_query($dbc, $query);
$i=0;
while($row = mysqli_fetch_array($data)) {
$row['tiempo'] = (float) $row['tiempo'];
$rows[$i]=array($row['tiempo'],(float)$row['Fp1Ref']);
$i++;
}
echo json_encode($rows);
The data i receive is this:
[[0,3001],[0.005,4937.22],[0.01,4130.55],[0.015,4213.15],[0.02,4010.61],[0.025,3914.34],[0.03,3785.33],[0.035,3666.13],[0.04,3555.25],[0.045,3447.77]]
So i think is the proper way to pass data for the chart, so i don't quite get whats wrong, thank you in advance.
I think the problem is that when your requestData() function is fired the chart variable still isn't fully built and doesn't know it has the series property.
To fix this, instead of chart in your requestData() function, reference this (which means the chart object in that context).
I tried this out in jsfiddle here http://jsfiddle.net/elcabo/p2r6g/.
Also post the js code below.
$(function () {
$(document).ready(function() {
//Function bits
function requestData(event) {
var tiemposAlAzar = [[10,20],[20,50]];
//The 'this' will refer to the chart when fired
this.series[0].setData(tiemposAlAzar);
};
var chart;
//Chart bits
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
events:{
load: requestData
}
},
xAxis: {},
yAxis: {
title: {
text: 'Value'
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
});
This url may help you to create dynamic highchart that need to pull data from database.
In json.php code you can put your sql query and replace static array to dynamic array
http://www.kliptu.com/free-script/dynamic-highchart-example-with-jquery-php-json
The example also shows how to manage multiple series with json.
And tooltips with all series data at mouse point.
You can modify example as per your script requirement.