Highchart not showing - laravel - php

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)

Related

Using highcharts with laravel blade with arrays

Hey guys I'm trying to attach a highchart in my blade template that looks like something like this
<body>
...
<div id="chart_div" style="width: 500px;height: 220px;"></div>
<div id="test_length">Test Length: </div>
<script type="text/javascript">
$(function () {
var myData = {!! json_encode($data['income_data']) !!};
$('#test_length').append(myData.length); //This shows the number on
var chart = Highcharts.chart('chart_div', {
credits: false,
title: {
text: ''
},
yAxis: {
labels: {
enabled: true,
formatter: function () {
return this.value;
}
},
gridLineWidth: 1,
minorGridLineWidth: 0,
title: {
text: ''
},
},
plotOptions: {
series: {
animation: false
}
},
series: [{
showInLegend: false,
data: myData,
tooltip: {
valueDecimals: 5
}
}]
});
});//end onload
</script>
</body>
</html>
I did a dd(json_encode($data['income_data'])); and the output looks like this
var myData output
"[["2012-11-30","10154.01"],["2012-12-31","10332.01"],["2013-01-31","10622.72"],["2013-02-28","10865.79"],["2013-03-31","10939.57"],["2013-04-30","10967.78"],["2013-05-31","11159.82"],["2013-06-30","10981.49"],["2013-07-31","11229.1"],["2013-08-31","11220.21"],["2013-09-30","11443.22"],["2013-10-31","11901.36"],["2013-11-30","12125.58"],["2013-12-31","12322.39"],["2014-01-31","12386.36"]]"
I suspect it's something to do with how I am passing my data to the highcharts library between the encoding where it's an array and not a JSON. Any help would be much appreciated as I have been trying to solve this for hours with no luck!

how can I modify my function via ajax?

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
}]
});
});
});

Ajax with HighCharts setData on Symfony 2

I have a problem on my HighCharts graph with JSON data. To explain a litle bit : I have a form, when I submit this form I send my data to my controller with Ajax, I treat them and I return the new array of data for my highcharts graph, but when I use setData function with my new array the graph disappear and the new data aren't displayed.
Here is my ajax function and my test to set the new data into my graph :
$('#gestion .l-gestion-content-form #form-add-informations .btn-validation').click(function(e) {
e.preventDefault();
var chart = $('#hightchart-graf').highcharts();
var dataActionForm = $('#form-add-informations').attr('action').split("/");
var url_ajax = Routing.generate('gestion_view', { dossier: dataActionForm[4], fille: dataActionForm[5] });
var formData = $('#form-add-informations').serializeArray();
$.ajax({
type: "POST",
dataType: 'json',
url: url_ajax,
data: formData,
success: function(msg)
{
console.log(msg['infosArray']);
var test = [ msg['infosArray'].join(',') ];
console.log(test);
console.log('---------------------------------------------');
console.log(msg.infosArray);
var test2 = msg.infosArray.join(',');
var test3 = test2.replace('"', '');
console.log(test2);
chart.series[0].setData( [ msg.infosArray.join(',') ] );
//[ {{ msg.infosArray | join(',') }} ]
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('ERROR');
}
});
});
All my data are stored in the array named msg.infosArray or msg['infosArray'] and the first console.log return an array like this :
["[Date.UTC(2015,11,23),80.00]", "[Date.UTC(2015,11,23),89.00]", "[Date.UTC(2015,11,25),150.00]", "[Date.UTC(2015,11,28),45.00]", "[Date.UTC(2015,11,29),169.00]", "[Date.UTC(2015,11,29),189.00]", "[Date.UTC(2015,11,29),196.00]", "[Date.UTC(2015,11,29),200.00]", "[Date.UTC(2015,11,29),205.00]", "[Date.UTC(2015,11,30),210.00]", "[Date.UTC(2015,11,31),225.00]", "[Date.UTC(2016,0,1),250.00]", "[Date.UTC(2016,0,2),25.00]", "[Date.UTC(2016,0,3),259.00]", "[Date.UTC(2016,0,5),25.00]", "[Date.UTC(2016,0,6),250.00]", "[Date.UTC(2016,0,7),25.00]", "[Date.UTC(2016,0,8),250.00]", "[Date.UTC(2016,0,9),25.00]", "[Date.UTC(2016,0,10),250.00]", "[Date.UTC(2016,0,11),25.00]", "[Date.UTC(2016,0,12),250.00]", "[Date.UTC(2016,0,25),25.00]", "[Date.UTC(2016,0,26),250.00]"]
So I tried to escape " and ' or to join the array but nothing work. Somebody know how can I set the new data, or where I commited a fault ?
Maybe i got a bad response from my Controller ?
Thanks
You need to convert string of javascript code to array of javascript.
I wrote a demo version which converts string to javascript code. and draws chart as expected. Do not focus on the labels it's a dummy data.
JSFiddle Demo
$(function () {
var data = ["[Date.UTC(2015,11,23),80.00]", "[Date.UTC(2015,11,23),89.00]", "[Date.UTC(2015,11,25),150.00]", "[Date.UTC(2015,11,28),45.00]", "[Date.UTC(2015,11,29),169.00]", "[Date.UTC(2015,11,29),189.00]", "[Date.UTC(2015,11,29),196.00]", "[Date.UTC(2015,11,29),200.00]", "[Date.UTC(2015,11,29),205.00]", "[Date.UTC(2015,11,30),210.00]", "[Date.UTC(2015,11,31),225.00]", "[Date.UTC(2016,0,1),250.00]", "[Date.UTC(2016,0,2),25.00]", "[Date.UTC(2016,0,3),259.00]", "[Date.UTC(2016,0,5),25.00]", "[Date.UTC(2016,0,6),250.00]", "[Date.UTC(2016,0,7),25.00]", "[Date.UTC(2016,0,8),250.00]", "[Date.UTC(2016,0,9),25.00]", "[Date.UTC(2016,0,10),250.00]", "[Date.UTC(2016,0,11),25.00]", "[Date.UTC(2016,0,12),250.00]", "[Date.UTC(2016,0,25),25.00]", "[Date.UTC(2016,0,26),250.00]"];
//t = t.map(function(element){return eval(element);});
data = data.map(function (e) {
return eval(e);
});
data = data.map(function (e) {
return [(new Date(e[0])).toLocaleString(), e[1]]
});
var categories = data.map(function (e) {
return (new Date(e[0])).toLocaleString()
});
// t[0] = [date = new Date(t[0])];
$('#container').highcharts({
title: {
text: 'Monthly Average Temperature',
x: -20 //center
},
subtitle: {
text: 'Source: WorldClimate.com',
x: -20
},
xAxis: {
categories: categories
},
yAxis: {
title: {
text: 'Temperature (°C)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: '°C'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: 'Tokyo',
data: data
}]
});
});

Highstock - How to add multiple series with JSON-Array

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.

Highcharts with 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.

Categories