Highchart not working (Codeigniter - JSON - Bootstrap) - php

I have a problem with my highchart, that is my chart doesn't appear. I use Codeigniter and I convert the data (from table) to JSON. I wang to show the Population and Amount based on Date
Here is my JSON data :
[{
"name":"Date",
"data":["27-OCT-14","28-OCT-14","29-OCT-14","30-OCT-14","31-OCT-14","01-NOV-14","02-NOV-14"]
},
{
"name":"Population",
"data":[6171,6990,6882,6889,6860,7619,6698]
},
{"name":"Amount",
"data":[361154716.01,409210099.77,407191552.71,416366585.57,418588842.18,435168113.68,402163667.57]
}]
This is my CONTROLLER that i used to encode_json
function daily(){
$data=array(
'title'=>'SOA_OTC - Daily',
'=>$this->model_app->get_Soa_Daily()
);
$category = array();
$category['name'] = 'Date';
$series1 = array();
$series1['name'] = 'Population';
$series2 = array();
$series2['name'] = 'Amount';
foreach($data['day']['START_EXECUTION'] as $row){
$category['data'][] = $row;
}
foreach($data['day']['NUM_OF_POPULATION'] as $row){
$series1['data'][] = $row;
}
foreach($data['day']['SUM_AMOUNT'] as $row){
$series2['data'][] = $row;
}
$result = array();
array_push($result,$category);
array_push($result,$series1);
array_push($result,$series2);
print json_encode($result, JSON_NUMERIC_CHECK);
$this->load->view('element/v_header',$data);
$this->load->view('pages/v_soaotc_daily');
$this->load->view('element/v_footer');
}
And this is my Highchart script in VIEW :
script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'containers',
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Project Requests',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Requests'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
$.getJSON('daily', function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.series[1] = json[2];
var chart = new Highcharts.Chart(options);
});
});
</script>
<div id="containers" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
Is there something wrong with my code? Very appreciate for your help.
Thanks

options.series is an empty array, you have to push into it:
$.getJSON('daily', function(json) {
options.xAxis.categories = json[0]['data'];
options.series.push(json[1]);
options.series.push(json[2]);
var chart = new Highcharts.Chart(options);
});

Related

Highchart not load JSON data

I have a page that uses highcharts pie chart with JSON data in it, My chart is not showing in browser but json data is showing like this :
[{"type":"pie","name":"Progress Fisik","data":[["rencana",89.4554],["realisasi",82.1436]]}]
Here my chart.js:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'donut_chart',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
credits: {
enabled: false
},
exporting: {
enabled: false
},
title: {
text: 'Progres Fisik',
align: 'center',
verticalAlign: 'middle'
},
plotOptions: {
pie: {
allowPointSelect: false,
startAngle: 180,
innerSize: '70%',
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function() {
return '<b>' + this.point.name+ '</b> : '+ this.point.y;
}
}
}
},
series: [{
type: 'pie',
innerSize: '50%',
colorByPoint: true,
data: []
}]
}
$.getJSON("data.php", function(json) {
options.series = json;
chart = new Highcharts.Chart(options);
});
});
And Here data.php :
include 'db-config.php';
$balai = mysqli_real_escape_string($config, $_GET['balai']);
$query = mysqli_query($config, "SELECT* FROM data_balai WHERE kode_balai='$balai'");
$rows['type'] = 'pie';
$rows['name'] = 'Progress Fisik';
while ($r = mysqli_fetch_assoc($query)) {
$rows['data'][0] = array('rencana', $r['ren_fisik']);
$rows['data'][1] = array('realisasi', $r['real_fisik']);
}
$rslt = array();
array_push($rslt, $rows);
print json_encode($rslt, JSON_NUMERIC_CHECK);
mysqli_close($config);
What do i need to do to fix my code above?

Filter dynamic graph from input data with ajax and PHP

I have made the code to draw a graph using the data obtained from a query in the database.
HTML:
<div>
<canvas id="mycanvas" height="150"></canvas>
</div>
PHP
$result = $mysqli->query("SELECT COUNT(social_id) as total, DATE_FORMAT(login_at, '%d-%m') as datee
FROM social_users_connections
WHERE login_at < DATE_ADD(NOW(), INTERVAL +1 MONTH)
AND client_id = $clientID
GROUP BY datee
ORDER BY login_at");
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
// print_r($data);
//now print the data
print json_encode($data);
AJAX:
$(document).ready(function () {
Chart.defaults.scale.ticks.beginAtZero = true;
$.ajax({
url: "view/ajax/php/data.php",
method: "GET",
success: function (data) {
console.log(data);
var player = [];
var score = [];
for (var i in data) {
player.push(data[i].total);
score.push(data[i].datee);
}
var chartdata = {
labels: score,
datasets: [{
label: 'Client Connections',
backgroundColor: 'rgba(0, 158, 251, 0)',
borderColor: 'rgba(0, 158, 251, 1)',
hoverBackgroundColor: 'rgba(0, 158, 251, 0)',
hoverBorderColor: 'rgba(0, 158, 251, 1)',
data: player
}]
};
var chartOptions = {
legend: {
display: true,
position: 'top',
labels: {
boxWidth: 80,
fontColor: 'black'
}
},
scales: {
xAxes: [{
gridLines: {
display: false,
color: "black"
},
scaleLabel: {
display: true,
labelString: "Fecha"
}
}],
yAxes: [{
gridLines: {
color: "black",
borderDash: [2, 5]
},
scaleLabel: {
display: true,
labelString: "Número de conexiones"
},
ticks: {
stepSize: 5
}
}]
}
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'line',
data: chartdata,
options: chartOptions
});
},
error: function (data) {
console.log(data);
}
});
});
Result:
What I need to do is add 2 input for the user to choose two dates and show a certain range. I tried to pass the input values through ajax to the PHP script to change the query but without success.
I tried this too:
HTML:
<input class="text-center" name="filter_date_from" type="date" id="filter_date_from" placeholder="fecha">
<input class="text-center" name="filter_date_to" type="date" id="filter_date_to" placeholder="fecha">
<button class="btn btn-primary" onclick="filterGraph()">Filtrar</button>
AJAX:
<script>
function filterGraph() {
var datefrom = document.getElementById('filter_date_from').value;
var dateto = document.getElementById('filter_date_to').value;
Chart.defaults.scale.ticks.beginAtZero = true;
$.ajax({
url: "view/ajax/php/data_filter.php",
method: "GET",
data: {
datefrom : datefrom,
dateto : dateto
},
success: function (data) {
console.log(data);
var player = [];
var score = [];
for (var i in data) {
player.push(data[i].total);
score.push(data[i].datee);
}
var chartdata = {
labels: score,
datasets: [{
label: 'Client Connections',
backgroundColor: 'rgba(0, 158, 251, 0)',
borderColor: 'rgba(0, 158, 251, 1)',
hoverBackgroundColor: 'rgba(0, 158, 251, 0)',
hoverBorderColor: 'rgba(0, 158, 251, 1)',
data: player
}]
};
var chartOptions = {
legend: {
display: true,
position: 'top',
labels: {
boxWidth: 80,
fontColor: 'black'
}
},
scales: {
xAxes: [{
gridLines: {
display: false,
color: "black"
},
scaleLabel: {
display: true,
labelString: "Fecha"
}
}],
yAxes: [{
gridLines: {
color: "black",
borderDash: [2, 5]
},
scaleLabel: {
display: true,
labelString: "Número de conexiones"
},
ticks: {
stepSize: 5
}
}]
}
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'line',
data: chartdata,
options: chartOptions
});
},
error: function (data) {
console.log(data);
}
});
}
</script>
PHP:
$date_from = $_POST['datefrom'];
$date_to = $_POST['dateto'];
$from = date('d-m', $date_from);
$to = date('d-m', $date_to);
$result = $mysqli->query("SELECT COUNT(social_id) as total, DATE_FORMAT(login_at, '%d-%m') as datee
FROM social_users_connections
WHERE DATE_FORMAT(login_at, '%d-%m') BETWEEN '$from' AND '$to'
AND client_id = '$clientID'
GROUP BY datee
ORDER BY login_at");
echo $result;
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
// print_r($data);
//now print the data
print json_encode($data)
;
But i have this error y at console:
GET http://35.177.140.48/view/ajax/php/data_filter.php?datefrom=2018-04-01&dateto=2018-04-26 500 (Internal Server Error)
I hope someone can guide me on how to do it.
Thanks in advance.

How to add php data into highchart js file in php

my code:
series: [{
name: 'Brands',
colorByPoint: true,
<?php
$models="SELECT * FROM purchase_info GROUP BY model_name";
$models_querry=mysql_query($models);
while($models_data=mysql_fetch_assoc($models_querry))
{
$model_name[]=$models_data['model_name'];
}
?>
data: [{
name: ['<?php echo join($model_name, ',') ?>'],
y: 56.33,
drilldown: 'Hero Honda'
}]
}],
In my project i'm using high charts, in that how can i add php data into that, i just collect all data and saved into one variable named as $model_name[], after that i pass the array value into data, but in that it will not spitted, all data's are echoed into single one.
Use ajax for that..see the script code
$.ajax({
type: "POST",
url: 'ajax.php',
success: function(data) {
a = jQuery.parseJSON(data);
i=0;
$.each( a.total_potential_score, function( key, val ) {
data1[i] = parseFloat(val);
i++;
});
rasterize_function(data1);
}
});
Ajax file look like this
$a[0] = "1";
$a[1] = "2";
$a1['total_potential_score'][0] = "1";
$a1['department_name'][0] = "aaaaa";
$a1['total_potential_score'][1] = "3";
$a1['department_name'][1] = "bbbbb";
echo json_encode($a1);
function for the highchart displayed here
function rasterize_function(data1) {
var seriesArray = [];
$.each( data1, function( key, val ) {
seriesArray.push({
name: "aaaa",
data: [val],
animation: false,
dataLabels: {
enabled: true,
rotation: -90,
color: '#FFFFFF',
align: 'right',
x: 4,
y: 10,
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
});
});
$('#container').highcharts({
chart: {
type: 'column',
width: 700,
height: 400,
borderWidth: 0
},
title: {
text: 'sector',
align: 'left'
},
subtitle: {
text: ''
},
xAxis: {
categories: ['College, Personal Development and Career Scores'],
},
yAxis: {
min: 0,
title: {
text: 'Potential Score'
}
},
legend: {
layout: 'horizontal',
backgroundColor: '#FFFFFF',
verticalAlign: 'bottom',
x: 10,
y: 7,
floating: false,
shadow: true
},
tooltip: {
formatter: function() {
return ''+
this.x +': '+ this.y +' points';
}
},
plotOptions: {
column: {
animation: false,
pointPadding: 0.2,
borderWidth: 0
}
},
series:seriesArray
});
}

Highcharts Data (using PHP JSON MYSQL)

When I used "data.php" data from the file itself doesn't read. But when I use "data.json" data from that file are showed in highcharts
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("***data.php***", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Revenue vs. Overhead',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
yAxis: {
title: {
text: 'No. of Events'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
plotOptions: {
column: {
stacking: 'normal',
dataLabels: {
enabled: true,
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
style: {
textShadow: '0 0 3px black'
}
}
}
},
series: json
});
});
});
data.json.....................................
[{
"name": "Revenue",
"data": [23987, 24784, 25899, 25569, 25897, 25668, 24114, 23899, 24987, 25111, 25899, 23221]
}, {
"name": "Overhead",
"data": [21990, 22365, 21987, 22369, 22558, 22987, 23521, 23003, 22756, 23112, 22987, 22897]
}];
data.php......................
<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("highcharts", $con);
$sth = mysql_query("SELECT revenue FROM projections_sample");
$rows = array();
$rows['name'] = 'Revenue';
while($r = mysql_fetch_array($sth)) {
$rows['data'][] = $r['revenue'];
}
$sth = mysql_query("SELECT overhead FROM projections_sample");
$rows1 = array();
$rows1['name'] = 'Overhead';
while($rr = mysql_fetch_assoc($sth)) {
$rows1['data'][] = $rr['overhead'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
Get the value from PHP first by using AJAX. Like this below:
$(function () {
var chart;
$(document).ready(function(){
$.ajax({
dataType: 'json',
url: 'data.php',
success: function(jsondata){
$.getJSON("***jsondata***", function(json){
// Your highchart codes here...
});
});
});
});

Convert Highchart to multiple y axis

I have a working graph using Highcharts with data from a mySQL database. I need it now to view the lines on different axis so that the chart is better laid out.
Here's my code and JSFiddle for the graph with my data:
http://jsfiddle.net/petenaylor/tGfau/3/
(function($){ // encapsulate jQuery
$(function() {
var seriesOptions = [],
yAxisOptions = [],
seriesCounter = 0,
names = ['Electric', 'Oil', 'Gas'],
colors = Highcharts.getOptions().colors;
$.each(names, function(i, name) {
$(function() {
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function(data) {
// Create the chart
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'container',
zoomType: 'x'
},
rangeSelector : {
selected : 12
},
title : {
text : 'Energy Prices'
},
series : [{
name : 'Electric',
<?php
$result = mysql_query (" SELECT * FROM energyprices ORDER BY id ASC") or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
extract($row);
$date = strtotime($row['pDate']);
$date = $date."000"; // convert from Unix timestamp to JavaScript time
$data1[] = "[$date, $electric]";
}
?>
data: [<?php echo join($data1, ',') ?>],
tooltip: {
valueDecimals: 2
}
},{
name : 'Oil',
<?php
$result = mysql_query (" SELECT * FROM energyprices ORDER BY id ASC") or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
extract($row);
$date = strtotime($row['pDate']);
$date = $date."000"; // convert from Unix timestamp to JavaScript time
$data2[] = "[$date, $oil]";
}
?>
data: [<?php echo join($data2, ',') ?>],
tooltip: {
valueDecimals: 2
}
},{
name : 'Gas',
<?php
$result = mysql_query (" SELECT * FROM energyprices ORDER BY id ASC") or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
extract($row);
$date = strtotime($row['pDate']);
$date = $date."000"; // convert from Unix timestamp to JavaScript time
$data3[] = "[$date, $gas]";
}
?>
data: [<?php echo join($data3, ',') ?>],
tooltip: {
valueDecimals: 2
}
}]
});
});
});
});
// create the chart when all data is loaded
function createChart() {
chart = new Highcharts.StockChart({
chart: {
renderTo: 'container'
},
rangeSelector: {
selected: 4
},
/*yAxis: {
labels: {
formatter: function() {
return (this.value > 0 ? '+' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},*/
yAxis: [{ // Primary yAxis
labels: {
formatter: function() {
return (this.value > 0 ? '+' : '') + this.value + '%';
},
style: {
color: '#89A54E'
}
},
title: {
text: 'Electric',
style: {
color: '#89A54E'
}
},
opposite: true
}, { // Secondary yAxis
gridLineWidth: 0,
title: {
text: 'Oil',
style: {
color: '#4572A7'
}
},
labels: {
formatter: function() {
return this.value;
},
style: {
color: '#4572A7'
}
}
}, { // Tertiary yAxis
gridLineWidth: 0,
title: {
text: 'Gas',
style: {
color: '#AA4643'
}
},
labels: {
formatter: function() {
return this.value;
},
style: {
color: '#AA4643'
}
},
opposite: true
}],
plotOptions: {
series: {
compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: seriesOptions
});
}
});
})(jQuery);
As you can see this works as it should, however, I need this to function like the below example. It's important that I have the y axis showing the values and the zoom must work. I have tried to adapt the below code with my own data but I get the issue unresponsive script. I think my data could be too much for the chart to handle.
http://jsfiddle.net/petenaylor/c73u5/5/
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
zoomType: 'xy'
},
title: {
text: 'Average Monthly Weather Data for Tokyo'
},
subtitle: {
text: 'Source: WorldClimate.com'
},
xAxis: [{
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
}],
yAxis: [{ // Primary yAxis
labels: {
formatter: function() {
return this.value +'°C';
},
style: {
color: '#89A54E'
}
},
title: {
text: 'Temperature',
style: {
color: '#89A54E'
}
},
opposite: true
}, { // Secondary yAxis
gridLineWidth: 0,
title: {
text: 'Rainfall',
style: {
color: '#4572A7'
}
},
labels: {
formatter: function() {
return this.value +' mm';
},
style: {
color: '#4572A7'
}
}
}, { // Tertiary yAxis
gridLineWidth: 0,
title: {
text: 'Sea-Level Pressure',
style: {
color: '#AA4643'
}
},
labels: {
formatter: function() {
return this.value +' mb';
},
style: {
color: '#AA4643'
}
},
opposite: true
}],
tooltip: {
formatter: function() {
var unit = {
'Rainfall': 'mm',
'Temperature': '°C',
'Sea-Level Pressure': 'mb'
}[this.series.name];
return ''+
this.x +': '+ this.y +' '+ unit;
}
},
legend: {
layout: 'vertical',
align: 'left',
x: 120,
verticalAlign: 'top',
y: 80,
floating: true,
backgroundColor: '#FFFFFF'
},
series: [{
name: 'Rainfall',
color: '#4572A7',
type: 'column',
yAxis: 1,
data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}, {
name: 'Sea-Level Pressure',
type: 'spline',
color: '#AA4643',
yAxis: 2,
data: [1016, 1016, 1015.9, 1015.5, 1012.3, 1009.5, 1009.6, 1010.2, 1013.1, 1016.9, 1018.2, 1016.7],
marker: {
enabled: false
},
dashStyle: 'shortdot'
}, {
name: 'Temperature',
color: '#89A54E',
type: 'spline',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}]
});
});
});
Can anyone help?
Many thanks
Pete
I think this is what you want: http://jsfiddle.net/mxrhS/
I did it by defining 3 yaxis, and then setting each series to use a different yaxis:
yAxis:[{opposite:false},{opposite:true},{opposite:true,offset:50}],
and
series: [{
name: 'Electric',
yAxis:0,

Categories