Passing array data to Morris Chart using JSON - php

I want to pass dynamic array data to Morris Charts from my Ajax Success return.
I arrive to get all data for the line chart.
How to do with this code to send data.json and data.y in the this.createAreaChartDotted parameters?
!function($) {
"use strict";
var MorrisCharts = function() {};
//creates area chart with dotted
MorrisCharts.prototype.createAreaChartDotted = function(element, pointSize, lineWidth, data, xkey, ykeys, labels, Pfillcolor, Pstockcolor, lineColors) {
Morris.Area({
element: element,
pointSize: 3,
lineWidth: 1,
data: data,
xkey: xkey,
ykeys: ykeys,
labels: labels,
hideHover: 'auto',
pointFillColors: Pfillcolor,
pointStrokeColors: Pstockcolor,
resize: true,
gridLineColor: '#eef0f2',
lineColors: lineColors
});
},
MorrisCharts.prototype.init = function() {
var id_transmetteur = $('#id_transmetteur').val();
var table_name = $('#table_name').val();
var category_table = $('#category_table').val();
$.ajax({
method:"post",
dataType: 'json',
url: $('#ajax').val()+'getDataCapteurs.php',
success: function(data){
if(data.status == 'success'){
console.log(data.json); //Replace $areaDotData
console.log(data.y); //Replace ['a', 'b'] in this.createAreaChartDotted()
} else if(data.status == 'error'){
if(data.messages.length>0){
var i;
for (i = 0; i < data.messages.length; ++i) {
if(data.messages[i][0] == 'error'){
console.log('error');
}
}
}
}
}
});
//creating area chart with dotted
var $areaDotData = [
{ y: '2009', a: 10, b: 20 },
{ y: '2010', a: 75, b: 65 },
{ y: '2011', a: 50, b: 40 },
{ y: '2012', a: 75, b: 65 },
{ y: '2013', a: 50, b: 40 },
{ y: '2014', a: 75, b: 65 },
{ y: '2015', a: 90, b: 60 }
];
this.createAreaChartDotted('morris-area-with-dotted', 0, 0, $areaDotData, 'y', ['a', 'b'], ['Series A', 'Series B'],['#ffffff'],['#999999'], ['#52bb56', '#ebeff2']);
},
//init
$.MorrisCharts = new MorrisCharts, $.MorrisCharts.Constructor = MorrisCharts
}(window.jQuery),
//initializing
function($) {
"use strict";
$.MorrisCharts.init();
}(window.jQuery);
I tried to declare a variable after
MorrisCharts.prototype.init = function(){
var data_chart; ...} and in ajax success : data_chart = data.json but when I tested my variable, she is undefined.
Thanks for helps.

You won't be able to access that data from outside the success callback in your ajax call. So instead, do whatever you need to do within the success callback. Try initializing the Morris chart from within the ajax call.
!function($) {
"use strict";
var MorrisCharts = function() {};
//creates area chart with dotted
MorrisCharts.prototype.createAreaChartDotted = function(element, pointSize, lineWidth, data, xkey, ykeys, labels, Pfillcolor, Pstockcolor, lineColors) {
Morris.Area({
element: element,
pointSize: 3,
lineWidth: 1,
data: data,
xkey: xkey,
ykeys: ykeys,
labels: labels,
hideHover: 'auto',
pointFillColors: Pfillcolor,
pointStrokeColors: Pstockcolor,
resize: true,
gridLineColor: '#eef0f2',
lineColors: lineColors
});
},
MorrisCharts.prototype.init = function(data, yData) {
this.createAreaChartDotted('morris-area-with-dotted', 0, 0, data, 'y', yData, ['Series A', 'Series B'],['#ffffff'],['#999999'], ['#52bb56', '#ebeff2']);
},
//init
$.MorrisCharts = new MorrisCharts, $.MorrisCharts.Constructor =
MorrisCharts
}(window.jQuery),
function($) {
"use strict";
var id_transmetteur = $('#id_transmetteur').val();
var table_name = $('#table_name').val();
var category_table = $('#category_table').val();
$.ajax({
method:"post",
dataType: 'json',
url: $('#ajax').val()+'getDataCapteurs.php',
success: function(data){
if(data.status == 'success'){
var data = data.json;
var yData = data.y;
//Send data & Yaxis
$.MorrisCharts.init(data, yData);
} else if(data.status == 'error'){
if(data.messages.length>0){
var i;
for (i = 0; i < data.messages.length; ++i) {
if(data.messages[i][0] == 'error'){
console.log('error');
}
}
}
}
}
});
}(window.jQuery);

Related

How to update Chart.js based on dropdown list?

UPDATED
I have added a dropdown to my chart which allows the user to select among the available operator names.
I need your help so that when selecting an available operator name, the graphic is updated showing only the information of the selected operator.
From all my JSON response, for this example it should only show the information in a red box:
As you can see in the image, if I select the Luis operator, this graph should update and show me only the Luis operator (he has 2 work orders in finished state).
Below my report.js file which I use to make the graph.
getChartData () method:
I use ajax, basically I'm getting the data and loading my select with the names of the available operators.
renderChart () method:
 
I am passing it as a parameter "label and data" with these parameters I can make my graph also I am configuring some available options.
select.on ('change', function ():
here I do not understand how to tell my chart to update depending on the option selected, then I would have to call the renderChart method again to graph again with the selected data but it does not work, I do not know how to solve it, it is what I am trying.
report.js
function getChartData(user) {
$.ajax({
url: '/admin/reports/getChart/' + user,
type: 'GET',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
dataType: 'json',
success: function (response) {
console.log(response);
var data = [];
var labels = [];
for (var i in response.orders) {
data.push(response.orders[i].orders_by_user);
labels.push(response.orders[i].name);
$("#operator").append('<option value='+response.orders[i].id+'>'+response.orders[i].name+'</option>');
}
renderChart(data, labels);
},
error: function (response) {
console.log(response);
}
});
}
function renderChart(data, labels) {
var ctx = document.getElementById("orders").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Terminadas',
data: data,
borderColor: 'rgba(75, 192, 192, 1)',
backgroundColor: "#229954",
borderWidth: 1,
yAxisID: 'Ordenes',
xAxisID: 'Operarios',
}]
},
options: {
scales: {
yAxes: [{
id: "Ordenes",
ticks: {
beginAtZero: true
},
scaleLabel: {
display: true,
labelString: 'Ordenes'
}
}],
xAxes: [{
id: "Operarios",
scaleLabel: {
display: true,
labelString: 'Operarios'
}
}],
},
title: {
display: true,
text: "Ordenes en estado terminado"
},
legend: {
display: true,
position: 'bottom',
labels: {
fontColor: "#17202A",
}
},
}
});
function updateChart() {
myChart.destroy();
myChart = new Chart(ctx, {
type: document.getElementById("operator").value,
data: data
});
};
}
getChartData();
$('#operator').select2({
placeholder: 'Selecciona un operario',
tags: false
});
var select = $('#operator');
var pElem = document.getElementById('p')
select.on('change', function() {
var item = $(this).val();
pElem.innerHTML = 'selectedValue: ' + item;
var data = {
labels: labels,
datasets: data
}
var ctx = document.getElementById("orders").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: data
});
});
My select:
<select class="form-control" name="operator" id="operator">
<option></option>
</select>
I get lost trying to link the selected option and the information to show (update the graph). Could you please tell me how to solve this?
UPDATED 1
My select:
<select class="form-control" name="operator" id="operator">
<option></option>
</select>
Through ajax I load my select options:
for (var i in response.orders) {
order.push(response.orders[i].orders_by_user);
user.push(response.orders[i].name);
$("#operator").append('<option value='+response.orders[i].id+'>'+response.orders[i].name+'</option>');
}
renderChart(order, user);
With the answer you have given me, modify my report.js file exactly my function renderChart(order, user) and it is as follows:
function renderChart(order, user) {
var ctx = document.getElementById("orders").getContext('2d');
var myChart = new Chart(ctx, {
//code...
});
//my select
var selectOption = $('#operator');
selectOption.on('change', function() {
var option = $("#operator").val();
myChart.data.labels = option;
if (option == 'All') {
myChart.data.labels = user,
myChart.data.datasets[0].data = order;
} else {
myChart.data.labels = option;
myChart.data.datasets[0].data = order;
}
myChart.update();
});
}
The graph is updated incorrectly an error occurs you can see it in the image:
Obviously if I select the "All" option, it shows and graphs correctly, now if I select "jose" the following happens:
The graph does not respect the scale, I know that Jose has only 1 work order, and up to 2 on the scale.
On the x axis instead of showing me the name in this case "Jose" is showing me the selection id which in this case is 6.
The same happens with the option "Miguel".
Please help me correct this section:
var selectOption = $('#operator');
selectOption.on('change', function() {
var option = $("#operator").val();
myChart.data.labels = option;
if (option == 'All') {
myChart.data.labels = user,
myChart.data.datasets[0].data = order;
} else {
myChart.data.labels = option;
myChart.data.datasets[0].data = order;
}
myChart.update();
});
When the selected options changes, you must not destroy the chart. All you need to do is performing the following steps.
Change the data.labels
Change the data of the unique dataset
Update the chart itself
This is basically done as follows.
myChart.data.labels = <new labels>;
myChart.data.datasets[0].data = <new values>;
myChart.update();
The following example illustrates how this can be done in JavaScript.
orders = [
{ name: 'Luis', orders_by_user: '2' },
{ name: 'Jose', orders_by_user: '1' },
{ name: 'Miguel', orders_by_user: '3' }
];
const myChart = new Chart(document.getElementById('orders'), {
type: 'bar',
data: {
labels: orders.map(o => o.name),
datasets: [{
label: 'Terminadas',
data: orders.map(o => o.orders_by_user),
borderColor: 'rgba(75, 192, 192, 1)',
backgroundColor: "#229954",
borderWidth: 1,
yAxisID: 'Ordenes',
xAxisID: 'Operarios',
}]
},
options: {
scales: {
yAxes: [{
id: "Ordenes",
ticks: {
beginAtZero: true,
stepSize: 1
},
scaleLabel: {
display: true,
labelString: 'Ordenes'
}
}],
xAxes: [{
id: "Operarios",
scaleLabel: {
display: true,
labelString: 'Operarios'
}
}],
},
title: {
display: true,
text: "Ordenes en estado terminado"
},
legend: {
display: true,
position: 'bottom',
labels: {
fontColor: "#17202A",
}
},
}
});
orders.forEach(o => {
const opt = document.createElement('option');
opt.value = o.name;
opt.appendChild(document.createTextNode(o.name));
document.getElementById('operator').appendChild(opt);
});
function refreshChart(name) {
myChart.data.labels = [name];
if (name == 'All') {
myChart.data.labels = orders.map(o => o.name),
myChart.data.datasets[0].data = orders.map(o => o.orders_by_user);
} else {
myChart.data.labels = [name];
myChart.data.datasets[0].data = orders.find(o => o.name == name).orders_by_user;
}
myChart.update();
}
Operarios:
<select id="operator" onchange="refreshChart(this.value)">
<option>All</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="orders" height="90"></canvas>

jVectormap adding markers from database only adds one marker

I am trying to add markers from a MySQL database via PHP into jvectormap (version 2.0.2).
I'm not sure what I'm doing wrong but when I add the markers dynamically using .AddMarkers, only a single marker shows up, which is the last marker in the JSON response.
This is my code:
JavaScript:
$("#airportsmap").vectorMap({
map: "world_mill_en",
scaleColors: ["#eff0f1", "#eff0f1"],
normalizeFunction: "polynomial",
hoverOpacity: .7,
hoverColor: !1,
regionStyle: {
initial: {
fill: "#6673a7"
}
},
markerStyle: {
initial: {
stroke: "transparent"
},
hover: {
stroke: "rgba(112, 112, 112, 0.30)"
}
},
backgroundColor: "transparent",
markers:[]
});
function loadairportmarkers(){
$.ajax({
type: "POST",
url: "modules/getfavouriteairportsdash.php",
dataType: 'json',
cache: false,
success: function(response) {
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
addMapPoint(value[3], value[4], value[2]);
});
} else {
$.each(response.errors, function( index, value) {
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
}
})
}
function addMapPoint(lat, lon, title){
var map = $('#airportsmap').vectorMap('get', 'mapObject');
map.addMarkers([{ latLng: [lat, lon], name: title }], []);
}
PHP
$stmt = $mysqli->prepare("
SELECT .... query here
");
$stmt->bind_param('is', $uid,$emp);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_all())
{
$returnResult = $row;
}
}
mysqli_close($mysqli);
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
exit;
This results in the following JSON response:
{"result":[["HUEN","FAOR","Entebbe International Airport","0.042386","32.443501"],["GABS","FAOR","Modibo Keita International Airport","12.5335","-7.94994"]],"errors":false}

ChartJS and Ajax calls

I would like to make charts using ChartJS and PHP ( Silex Framework )
This is my ajax call
$.ajax({ url: 'stats',
data: {method: 'dossierRepartitionType'},
type: 'post',
datatype: 'json',
success: function(output) {
dataDossierRepartitionType=output;
},
error: function () {
alert("Oops there is an error.");
}});
This is my PHP function which i managed to call
public function dossier(){
$stmt = "SELECT count(*) FROM dossier GROUP BY typedossier";
$stmt = $this->db->prepare($stmt);
$rows=$stmt->execute();
$rows = $stmt->fetch(PDO::FETCH_NUM);
return ?????
}
And here is my chart :
var ctx = document.getElementById("myChart");
ctx.width = 400;
ctx.height = 400;
data = {
datasets: [{
data: [dataDossierRepartitionType, 20],
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(54, 162, 235)',
],
borderColor: [
'white',
'white',
],
borderWidth: 1
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [
'Red',
'Blue',
]
};
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: {
legend: {
labels: {
fontColor: "white",
fontSize: 18
}
},
maintainAspectRatio: false,
responsive: false
}
});
Route.php
$app->post('/stats', function () use ($app) {
session_start();
if(isset($_POST['method']) && !empty($_POST['method'])) {
$method = $_POST['method'];
switch($method) {
case 'dossierRepartitionType' :
$dossiers=$app['dao.dossier']->dossierRepartitionType();
break;
}
}
return new ResponseSilex("$dossiers");
});
So my AJAX call the route and then get the result of the function into $dossiers which is ouput in the Reponse, am i doing it right ?
How can i return an array with all the datas value for each count ?
I struggle to catch error and to find a proper way to bind MYSQL count value to my chart
Thank you
The main idea is that you should format your data in your model, then return JSON to the front end via json_encode. After that, you would parse the json in your ajax returns and then pass the appropriate data to the chart.
it's very easy, you need to modify your php code like this:
public function dossier(){
$stmt = "SELECT count(*) as total FROM dossier";
$stmt = $this->db->prepare($stmt);
$rows=$stmt->execute();
$number_of_rows = $rows->fetchColumn();
return json_encode(["total" => $number_of_rows]);
In your ajax petition you are specifying a "json" return so in your script php need's return a json.
$.ajax({ url: 'stats',
data: {method: 'dossierRepartitionType'},
type: 'post',
datatype: 'json',
success: function(output) {
dataDossierRepartitionType=output.total;
},
error: function () {
alert("Oops there is an error.");
}});
You should to receive a json from php with this structure
{total: rows_total}
so in your ajax response you'll receive that answer and you can get the data like this:
dataDossierRepartitionType=output.total;
Sorry for my english, hope can help you
You can send JSON data from php
Try this:
Php:
public function dossier(){
$stmt = "SELECT count(*) FROM dossier GROUP BY typedossier";
$stmt = $this->db->prepare($stmt);
$rows=$stmt->execute();
$rows = $stmt->fetch(PDO::FETCH_NUM);
exit(json_encode(array('counts' => $rows)));
}
After ajax successfully complete you need to initialize chart plugin inside success callback like below:
Ajax:
$.ajax({ url: 'stats',
data: {method: 'dossierRepartitionType'},
type: 'post',
datatype: 'json',
success: function(output) {
if (output.counts) {
dataDossierRepartitionType=output.counts.join();
alert(dataDossierRepartitionType)
initCharts(dataDossierRepartitionType);
}
},
error: function () {
alert("Oops there is an error.");
}});
Finally wrap chart initialization code inside callback function
Chart:
function initCharts(dataDossierRepartitionType){
var ctx = document.getElementById("myChart");
ctx.width = 400;
ctx.height = 400;
data = {
datasets: [{
data: [dataDossierRepartitionType, 20],
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(54, 162, 235)',
],
borderColor: [
'white',
'white',
],
borderWidth: 1
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [
'Red',
'Blue',
]
};
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: {
legend: {
labels: {
fontColor: "white",
fontSize: 18
}
},
maintainAspectRatio: false,
responsive: false
}
});
}

How to get percentage from data collected in ChartJS?

I'm having trouble with percentages.
Here's the data from my database:
Jobstreet - 2 (total number of users who pick this as source of job application)
Facebook - 1 (total number of users who pick this as source of job application)
Indeed.com - 1 (total number of users who pick this as source of job application)
The code I have seems to just append the percentage sign.
Now, I'm expecting to get something like this:
Jobstreet - 50% | Facebook - 25% | Indeed.com - 25%
And if you sum them up, you'll get 100%.
I don't know how to get that. Please help me with my problem.
Here's my code:
$(document).ready(function(){
$.ajax({
url: "/public/ajax/generateChart/",
method: "GET",
success: function(data) {
var source = [];
var count = [];
for(var i in data) {
source.push(data[i].source);
count.push(data[i].number);
}
var config = {
type: 'doughnut',
data: {
datasets: [{
data: count,
backgroundColor: [
'rgba(59, 89, 152, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255,1)',
'rgba(255, 159, 64, 1)'
]
}],
labels: source
},
options: {
responsive: true,
legend: {
position: 'bottom',
},
title: {
display: false,
text: 'Chart.js Doughnut Chart'
},
animation: {
animateScale: true,
animateRotate: true
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var total = dataset.data.reduce(function(previousValue, currentValue, currentIndex, array) {
return previousValue + currentValue;
});
var currentValue = dataset.data[tooltipItem.index];
var precentage = Math.floor(((currentValue/total) * 100)+0.5);
return ": " + precentage + "%";
}
}
}
}
};
var ctx = $('#chartCanvas');
window.myDoughnut = new Chart(ctx, config);
},
error: function(data) {
console.log(data);
}
});
});
You can accomplish that using the following tooltips label callback function and a chart plugin ...
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var label = data.labels[tooltipItem.index];
var _data = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
var data = /\./.test(_data) ? _data.toFixed(2) : _data;
return label + ' - ' + data + '%';
}
}
}
ᴄʜᴀʀᴛ ᴘʟᴜɢɪɴ
plugins: [{
beforeInit: function(c) {
var data = c.data.datasets[0].data
var data_sum = data.reduce((a, b) => a + b, 0);
var each_one = 100 / data_sum;
c.data.datasets[0].data = data.map(e => e * each_one);
}
}]
add the plugin followed by your chart options
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ
$(document).ready(function() {
$.ajax({
url: "https://istack.000webhostapp.com/json/t5.json",
method: "GET",
success: function(data) {
var source = [];
var count = [];
for (var i in data) {
source.push(data[i].source);
count.push(+data[i].number);
}
var config = {
type: 'doughnut',
data: {
datasets: [{
data: count,
backgroundColor: [
'rgba(59, 89, 152, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255,1)',
'rgba(255, 159, 64, 1)'
]
}],
labels: source
},
options: {
responsive: false,
legend: {
position: 'bottom',
},
title: {
display: false,
text: 'Chart.js Doughnut Chart'
},
animation: {
animateScale: true,
animateRotate: true
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var label = data.labels[tooltipItem.index];
var _data = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
var data = /\./.test(_data) ? _data.toFixed(2) : _data;
return label + ' - ' + data + '%';
}
}
}
},
plugins: [{
beforeInit: function(c) {
var data = c.data.datasets[0].data
var data_sum = data.reduce((a, b) => a + b, 0);
var each_one = 100 / data_sum;
c.data.datasets[0].data = data.map(e => e * each_one);
}
}]
}
var ctx = $('#chartCanvas');
window.myDoughnut = new Chart(ctx, config);
},
error: function(data) {
console.log(data);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="chartCanvas" height="200"></canvas>
$(document).ready(function() {
$.ajax({
url: "https://istack.000webhostapp.com/json/t5.json",
method: "GET",
success: function(data) {
var source = [];
var count = [];
for (var i in data) {
source.push(data[i].source);
count.push(+data[i].number);
}
var config = {
type: 'doughnut',
data: {
datasets: [{
data: count,
backgroundColor: [
'rgba(59, 89, 152, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255,1)',
'rgba(255, 159, 64, 1)'
]
}],
labels: source
},
options: {
responsive: false,
legend: {
position: 'bottom',
},
title: {
display: false,
text: 'Chart.js Doughnut Chart'
},
animation: {
animateScale: true,
animateRotate: true
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var label = data.labels[tooltipItem.index];
var _data = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
var data = /\./.test(_data) ? _data.toFixed(2) : _data;
return label + ' - ' + data + '%';
}
}
}
},
plugins: [{
beforeInit: function(c) {
var data = c.data.datasets[0].data
var data_sum = data.reduce((a, b) => a + b, 0);
var each_one = 100 / data_sum;
c.data.datasets[0].data = data.map(e => e * each_one);
}
}]
}
var ctx = $('#chartCanvas');
window.myDoughnut = new Chart(ctx, config);
},
error: function(data) {
console.log(data);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="chartCanvas" height="200"></canvas>

Dynamic column based highcharts feeding data with jquery and php

I am trying to build column based highcharts, and here is my code in jquery:
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
credits: {
enabled: false
},
title: {
text: 'PCP Histogram',
x: -20
},
xAxis: {
categories: [{}]
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
tooltip: {
formatter: function() {
var s = '<b>'+ this.x +'</b>';
$.each(this.points, function(i, point) {
s += '<br/>'+point.series.name+': '+point.y;
});
return s;
},
shared: true
},
series: [{},{}]
};
$.ajax({
url: "file.php",
type: "post",
dataType: "json",
success: function(data){
options.xAxis.categories = data.categories;
options.series[0].name = 'Avg1';
options.series[0].data = data.avg1;
options.series[1].name = 'Avg2';
options.series[1].data = data.avg2;
var chart = new Highcharts.Chart(options);
And I getting the data from file php like this:
file.php
$graph_data = array('categories'=>$categories, 'avg1'=>$avg, 'avg2'=>$avg);
print json_encode($graph_data, JSON_NUMERIC_CHECK);
It is working fine with two columns per category,
What I want now is: the graph_data can have n number of avg datas,
so basically it will be n number of columns.
$graph_data = array('categories'=>$categories, 'avg1'=>$avg1, ... 'avgn'=>$avgn);
When I do it manually it works, but I will not know how many of them will be there, so I want the code to do i.
Any idea how I can do it?
Any help appreciated.
make an array of avg instead of having avg1, avg2 etc....
$graph_data = array('categories'=>$categories, 'avgs'=>$array_of_avgs)
then in javascript side
success: function(data){
options.xAxis.categories = data.categories;
for(var i in data.avgs){
options.series[i].name = 'Avg'+i;
options.series[i].data = data.avgs[i];
}
var chart = new Highcharts.Chart(options);
And everything will be fine

Categories