JSON, Codeigniter, Highcharts and AJAX - javascript

I'm using CI (+HMVC) for showing a Highcharts with an ajax event on a form.
My pb is to create valids Series for the chart. I have to create 6 series from mysql DB. My chart code is inpired by
blank page highchart in using jquery to call json arrary.
My View
(<?=$instance_graph?> is everywhere because I want to be able to instance multiple charts)
$(document).ready(function() {
$('#submit<?=$instance_graph?>').click(function() {
$('#rendu_graph<?=$instance_graph?>').html('');
var form_data = {
from : $('#from[name=from<?=$instance_graph?>]').val(),
to : $('#to[name=to<?=$instance_graph?>]').val(),
parametre : $('#parametre[name=parametres<?=$instance_graph?>]').val(),
ajax : '1'
};
$.ajax({
url: "<?= site_url('graph_meteo/ajax_graph'); ?>",
type: 'POST',
async : false,
data: form_data,
dataType:'json',
success: function(data) {
//alert(msg) ;
//$('#rendu_graph<?=$instance_graph?>').html(msg);
var chartSeriesData=[];
$.each(data, function(i,item){
var series_name = item.name;
var series_data = item.data;
var series = {data: item.data,name:series_name};
chartSeriesData.push(series);
});
console.log(chartSeriesData) ;
chart = new Highcharts.Chart({ //Début du Highchar
chart: {
renderTo: 'rendu_graph<?=$instance_graph?>',
type: 'spline'
},
title: {
text: 'Graph'
},
subtitle: {
text: 'Title'
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'param 1'
}
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' + Highcharts.dateFormat('%a %d %b %H:%M', this.x) + ': ' + this.y + ' m';
}
},
series: chartSeriesData
})
The console.log of the series created :
[Object { data="[Date.UTC(2013,02,06,14,15),65.09375]", name="Station 1"}, Object { data="[Date.UTC(2013,02,06,14,15),65.09375]", name="Station 1"}, Object { data="[Date.UTC(2013,02,06,14,15),65.09375]", name="Station 1"}, Object { data="[Date.UTC(2013,02,06,14,30),63.425]", name="Station 1"}.
And of course I have one serie for each object with no plot:
edit :I'm looking for a way to have a nice working graph with these data ( 1 lines) and I want my code working for many lines/series. My big pb is to start from Query result to chart series format. An example could be nice answer.
I hope you could help me before I became mad!

First problem with your setup is that the data for each series is a string with an array in it. Currently it looks like:
{ data: "[Date.UTC(2013,02,06,14,15),65.09375]", name: "Station 1"}
The name looks ok, but the data should be a real javascript array, not a string. This is what you want it to look like:
{ data: [Date.UTC(2013,02,06,14,15),65.09375], name: "Station 1"}
When that is solved I think you should put all data-points in the same series-definition. So instead of:
{ data: [Date.UTC(2013,02,06,14,15),65.09375], name: "Station 1"},
{ data: [Date.UTC(2013,02,07,14,15),67.09375], name: "Station 1"}
You should have one series with many points:
{ data: [
[Date.UTC(2013,02,06,14,15),65.09375],
[Date.UTC(2013,02,07,14,15),67.09375],
<more data points here>],
name="Station 1"},

Related

Highchart showing up empty until button click

I have been customizing the following jsfiddle in order to display data from a database. http://jsfiddle.net/jlbriggs/7ntyzo6u/
I am using JSON in order to retrieve data in my database. In the jsfiddle, there are 3 charts which can be switched between by clicking buttons. But when you load the page, chart1 is the default chart showing. Now I have edited chart1 so that it will display my database data:
var chart,
chartOptions = {},
chartData = {};
chartData.chart2 = randomData(10, true);
chartData.chart3 = randomData(65, true, 300);
chartOptions.chart1 = {
chart: {
type: 'column'
},
title: {
text: 'Chart 1 Title'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Chart 1<br/>Y Axis'
}
},
series: [{
name: 'Chart 1 Series',
data: []
}]
};
var tableName = '<?php echo $tableName; ?>'
$.getJSON("../../companies/charts/Data.php", {id: escape(tableName)}, function(json) {
chartOptions.chart1.xAxis.categories = json[0]['data'];
chartOptions.chart1.series[0].data = json[6]['data'];
});
My problem is, that the chart shows up as empty after loading the page. Only when I click the chart1 button will the data show up. Can anyone tell me if this is because I am missing something after setting the xAxis and series data in the above code?
Since $.getJSON is asynchronous (see comment below) I have tried to now send the request using ajax instead. Below is my attempt, but this is flawed since the chart will now not even display data upon clicking the 'chart1' button. The chart does come up, but is empty:
chartOptions.chart1 = {
chart: {
type: 'column'
},
title: {
text: 'Chart 1 Title'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Chart 1<br/>Y Axis'
}
},
series: [{
name: 'Chart 1 Series',
data: []
}]
};
var tableName = '<?php echo $tableName; ?>'
$.ajax({
url: "../../companies/charts/Data.php",
data: {id: escape(tableName)},
dataType: "json",
async: false,
succes: function(data) {
chartOptions.chart1.xAxis.categories = json[0]['data'];
chartOptions.chart1.series[0].data = json[6]['data'];
}
});
Thanks in advance for your assistance!
My assumption is that since $.getJSON is asynchronous , the chart is already loaded before the data is populated.
You can try calling the setData method on the series inside the $.getJSON block.This will force a chart redraw :
chartOptions.chart1.series[0].setData(json[6]['data'],true);
Or try to send the request using $.ajax with async:false.Replace the following block with the $.getJSON block.
$.ajax({
url: "../../companies/charts/Data.php",
data: {id: escape(tableName)},
async:false
}).done(function() {
chartOptions.chart1.xAxis.categories = json[0]['data'];
chartOptions.chart1.series[0].data = json[6]['data'];
});
I think this should get you going.
Read more about it over here: jQuery.ajax

new Highcharts from jQuery AJAX request

I'm trying to display a new Highcharts. Usually I use data from local server and i'm able to load data this way:
data : <php echo $jsonEncoded['values']?>,
The problem is : I have to load data from a remote server and it doesn't work! I really don't understand why...
You will find below my code :
$.ajax({
url: 'myurl',
type: 'GET',
dataType : 'json',
success: function(json, statut){
data_day = json['day'];
data_values = json['js'];
data_start = json['start'];
options = {
chart: {
type: 'area',
renderTo: 'container_health',
},
titile: {
text: "text",
},
yAxis: {
title: {
text: 'Pourcentage'
},
max: 100,
},
series : [{
name: "test",
data: data_values,
pointStart: Data.UTC(data_start),
pointInterval: 24*3600*1000
},
]
};
chart = new Highcharts.Char(options);
}
Then I have 3 alerts:
alert(chart.series[0].pointInterval); //display well the date
alert(chart.series[0].data[0].y); //display undefined
alert(data_values); //display well values
So it seems, I don't have a problem when I want to access directly to a data from my JSON object (json['start']) but it seems it doesn't work when I try to access to my array from json['js']...
Is it a problem from Highcharts or the way to access to data?
EDIT :
All data don't work in options btw.
BR,

Set 2d json to highcharts

I use highcharts for draw charts. I have 2d json object and I don't know how to set this object to highcharts. And this is my json object data:
And I want my chart like this picture(column-parsed example of highchart):
And this is my code:
$.ajax({
url:"../../teachersem",
type:"get",
data:{
id:$.trim(tableData[0])
},
success:function(data){
$('div[class|="col-md-7 col-md-offset-3"]').css("display","none");
//console.log(data.accept);
//console.log(data.fail);
var accept=new Array();
var fail =new Array();
for (i = 0; i < data.accept.length; i++){
accept.push([data.accept[i].year, parseInt(data.accept[i].count)]);
alert("accept: "+data.accept[i].year+" "+parseInt(data.accept[i].count));
}
//console.log(accept.toString());
for (i = 0; i < data.fail.length; i++){
fail.push([data.fail[i].year, parseInt(data.fail[i].count)]);
alert("fail: "+data.fail[i].year+" "+parseInt(data.fail[i].count));
}
$('#container').highcharts({
chart: {
type: "column"
},
title: {
text: "Student data"
},
xAxis: {
allowDecimals: false,
title: {
text: "Branch of studies"
}
},
yAxis: {
title: {
text: "Number of students"
}
},
series: [{
data: [accept,fail]
}],
});
},
error:
alert('error!')
})
});
But this has any result? please help,thank u!
You actually want two series: data parameters (one for each column).
The first column will be the accept data and the second column will be your fail data since I am guessing that your category label which in the example image is Apples will be a Branch of Studies.
Your series should look something similar to the following:
series: [{
name: "Accept",
data: accept,
},
{
name: "Fail",
data: fail,
}]
Your accept and fail arrays are currently arrays of arrays, but they can actually be a simple list as seen in the Highcharts demo here. You can then specify in the xAxis parameter the categories: that are your Branch of Studies.

How to implement Highcharts column-drilldown chart in Rails application?

I'm trying to implement a Highcharts Column-Drilldown Chart in my Rails application using lazy_high_charts. I want to display data that's being pulled from my database and stored in four arrays (areas, areaScores, departments, and deptScores). I'm having trouble converting the JS from the example (JSFiddle) listed on the highchart site into ruby. I have not been able to find any resources on creating a column-drilldown chart in ruby. Any help on how to integrate the drilldown chart into my ruby application would be highly appreciated.
I have included the sample JavaScript shown on the Highcharts demo page and my controller method that populates the four arrays with data and builds the highchart.
Highcharts Column-Drilldown Chart Example (Javascript)
$(function () {
Highcharts.data({
csv: document.getElementById('tsv').innerHTML,
itemDelimiter: '\t',
parsed: function (columns) {
var brands = {},
brandsData = [],
versions = {},
drilldownSeries = [];
// Parse percentage strings
columns[1] = $.map(columns[1], function (value) {
if (value.indexOf('%') === value.length - 1) {
value = parseFloat(value);
}
return value;
});
$.each(columns[0], function (i, name) {
var brand,
version;
if (i > 0) {
// Remove special edition notes
name = name.split(' -')[0];
// Split into brand and version
version = name.match(/([0-9]+[\.0-9x]*)/);
if (version) {
version = version[0];
}
brand = name.replace(version, '');
// Create the main data
if (!brands[brand]) {
brands[brand] = columns[1][i];
} else {
brands[brand] += columns[1][i];
}
// Create the version data
if (version !== null) {
if (!versions[brand]) {
versions[brand] = [];
}
versions[brand].push(['v' + version, columns[1][i]]);
}
}
});
$.each(brands, function (name, y) {
brandsData.push({
name: name,
y: y,
drilldown: versions[name] ? name : null
});
});
$.each(versions, function (key, value) {
drilldownSeries.push({
name: key,
id: key,
data: value
});
});
// Create the chart
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Browser market shares. November, 2013'
},
subtitle: {
text: 'Click the columns to view versions. Source: netmarketshare.com.'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: 'Total percent market share'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}%'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
},
series: [{
name: 'Brands',
colorByPoint: true,
data: brandsData
}],
drilldown: {
series: drilldownSeries
}
})
}
});
});
My Controller:
def generateOrgBreakdownReport
# First, query the database for the data you need for the report
#jsonanswerBRKD = queryDatabaseForOrgProgressReport()
# Second, process and combine data as needed for the report
#areaBreakdown, #deptBreakdown, #employBreakdown = computeAreaAndDeptPrepareScore(#jsonanswerBRKD)
# Third, you'll need to put the processed data into a format
# Highcharts will understand for the data series it uses
# for the graph.
#THESE ARRAYS HOLD THE NAMES AND SCORES OF AREAS AND DEPARTMENTS
#deptScores, #departments, #areaScores, #areas = cycleThroughProcessedDataAndCreateHighChartsDataSetsBreakdown(#areaBreakdown, #deptBreakdown, #employBreakdown)
# Last, we put the newly made data sets for Highcharts to work its magic.
#DONT KNOW HOW TO IMPLEMENT DRILLDOWN FOR RUBY
#orgBreakdown = LazyHighCharts::HighChart.new('column') do |f|
f.chart( type: 'column' )
f.xAxis(
title: { text: "Areas" },
type: 'category'
)
f.yAxis(
title: { text: "Preparedness Score (%)"},
)
f.series(
name: "Department Score",
colorByPoint: true,
data: #deptScores
)
f.series(
name: "Area Score",
data: #areaScores
)
f.title(
text: "Organizational Breakdown"
)
f.options[:xAxis][:categories] = #areas
f.drilldown({:series=>{
name:"Dept. Score",
data: #deptScore
}
})
end
end
Thanks,
Matt
I haven't used Lazy Highcharts, but assuming it mirrors the JSON from the JavaScript API you need to add the sub-series by name, e.g.
f.series(
name: "Department Score",
colorByPoint: true,
data: #deptScores,
drilldown: "subdept" #add this
)
Then you'll need to add drilldown data, and if Lazy Highcharts supports it, it might look something like this:
f.drilldown(
series: {
id: "subdept",
data: [
["One", 1],
["Two", 2],
["Three", 3]
]
}
)
See this basic drilldown fiddle to see how the resulting Javascript should look.
To get drilldown to work in Rails you have to make sure you include the drilldown module in your JavaScript manifest file (application.js).
I also had to download the file as it was not my highcharts module catalogue. You can find the file here: http://code.highcharts.com/modules/drilldown.js
Add this to application.js:
//= require highcharts/modules/drilldown
Outside of Rails you can include the drilldown module like this:
<script src="http://code.highcharts.com/modules/drilldown.js"></script>

Displaying a json file with highstock

I have some difficulties displaying a graph with Highstock. It seems like I can't have access to the x-axis part where the graph should be displayed. I am new with Highstocks so my code could seem like a mess but my idea was the following:
First access the json file from the server. Convert it in the right format [[datestamp, value], ....]. Then display the graph.
Here is my Json file (file.json):
[{"date":"2013-10-04T22:31:12.000Z","value":30000},{"date":"2013-10-04T22:31:58.000Z","value":35000},{"date":"2013-10-04T22:32:05.000Z","value":60000},{"date":"2013-10-04T22:32:12.000Z","value":45000}]
My code is the following:
$(function() {
chartOjb = new Object();
var mydata = [];
$.getJSON('file.json', function(data) {
$.each(data, function (index, item) {
chartOjb.name = getTimestamp(item.date);
chartOjb.data = item.value;
mydata.push({ x: chartOjb.name, y: parseFloat(chartOjb.data) });
});
$('#container').highcharts('StockChart', {
chart: {
type: 'candlestick',
zoomType: 'x'
},
navigator: {
adaptToUpdatedData: false,
series: {
data: mydata
}
},
scrollbar: {
liveRedraw: false
},
xAxis: {
type: 'datetime',
title: 'Time',
//minRange: 3600 * 1000/15 // one hour
},
rangeSelector : {
selected : 1
},
title : {
text : value
},
series : [{
name : 'Capacité',
data : data,
tooltip: {
valueDecimals: 2
}
}] }); });
});
Thank you very much for your help
Could you add your function getTimestamp()? Maybe there is something wrong.
Keep in mind that:
x-value should be timestamp,
when using a lot of objects { x: x, y: y }, set turboThreshold

Categories

Resources