Reputation: 111
I have and array of data and I want it to loop inside data[] for presenting a chart using Highchart.js
chart type is column
.
When passing data from controller to view I have printed the graph using below code but now since the data is coming from ajax request how can I process the data to make a graph.
I have created one results
array and loop through each data and pushed inside the results and passed it directly to data in generateGraph
function, but the graph is not working.
I am using ajax request to fetch data and pass it to the function defined for generating graph, below is my array data format.
Ajax request
$.ajax({
url : someurl,
dataType: "json",
method: 'post',
beforeSend: function() {
$("#loader").show();
},
success: function( data ) {
$("#loader").hide();
generateGraph(data);
}
});
array data
[
{
name: "Bestozyme",
number: "1",
},
{
name: "Sinarest-PD",
number: "1",
},
{
name: "Azithral",
number: "1",
},
{
name: "Lecope-M-Kid",
number: "1",
},
{
name: "Calpol (250 MG)",
number: "1",
},
{
name: "Calapure",
number: "1",
},
]
using php code in series
- data passing through rendering views from controller.
series: [{
name: 'Medicine',
color: '#F15C80',
data: [
<?php
foreach($data['medicine'] as $medi){
?>
['<?php echo $medi['name'];?>',<?php echo $medi['number'];?>],
<?php
}
?>
],
dataLabels: {
enabled: true,
rotation: -90,
color: '#FFFFFF',
align: 'right',
format: '{point.y}', // one decimal
y: 10, // 10 pixels down from the top
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
}]
highchart.js
function generateGraph(item){
let results=[];
item.forEach((val) => {
results.push([val.name,val.number])
});
Highcharts.chart('medicine', {
chart: {
type: 'column'
},
title: {
text: ' '
},
xAxis: {
type: 'category',
labels: {
rotation: -45,
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
},
yAxis: {
min: 0,
title: {
text: 'Medicine'
}
},
legend: {
enabled: false
},
tooltip: {
pointFormat: '<b>{point.y}</b>'
},
series: [{
name: 'Medicine',
color: '#F15C80',
data: results,
dataLabels: {
enabled: true,
rotation: -90,
color: '#FFFFFF',
align: 'right',
format: '{point.y}', // one decimal
y: 10, // 10 pixels down from the top
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
}]
});
}
Upvotes: 1
Views: 650
Reputation: 11633
Notice that Highcharts requires the y
data value in a number format, not string. Try this approach:
let results=[];
item.forEach((val) => {
results.push([val.name, parseInt(val.number)])
});
Demo: https://jsfiddle.net/BlackLabel/Lds9cyau/
Upvotes: 1