new Highcharts from jQuery AJAX request - javascript

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,

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

Importing Categorical data from SQL, to C3.js, using JSON

I'm currently working on dynamically building column graphs in MVC, using C3 Charts. While I can bring the data from the database using AJAX/JSON, I am able to bind only the Y-Axis coordinates using the JSON property of C3, not the X-Axis categories.
What I want to do: Build column charts dynamically. For instance, the marks of students of multiple years will be calibrated as (Year 1: 50),(Year 2: 100) and so on, with the first part (category:Year) going on the X-Axis and the numeric part (Marks) going to the Y-Axis. The number of such combinations is dynamic, depending on the user's requirements (brought from the database as two columns, with multiple rows).
Problems I'm running into:
Specifying two different data types in the keys renders the non-numeric part (the category) as a separate series altogether, which I don't want and which isn't even working.
Whatever I do, the X-Axis comes with whole numbers depending on the number of columns visible. I'd like to change that to the actual category names.
Here is what I am doing. I took inspiration from Daniel's method here (https://groups.google.com/d/msg/c3js/RV1X18GZoGY/-p39m9Ngt-gJ)
$.ajax({
url: <Method in Controller here>,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parameters),
success: function (data) {
var myData = jQuery.parseJSON(data);
var testJson = $.map(myData, function (item) {
return {
Year: item.Year,
Marks: item.Marks
}
});
var chart = c3.generate({
bindto: '#chart',
size: {
width: 800
},
data: {
json: testJson,
mimeType: 'json',
keys: {
value: ['Marks']
},
}
});
}
});
Looking forward to some assistance. Thanks in advance!
Edit: I want the data to look like this in the end:
Sample Chart
You can try the following code:
var jsonTest = [
{ year: 1, marks: 50 },
{ year: 2, marks: 70 },
{ year: 3, marks: 75 },
{ year: 4, marks: 45 },
];
// The variable name chart will automatically bind itself to an id = chart
var chart = c3.generate({
data: {
type : 'bar',
json: jsonTest,
keys: {
x: 'year',
value: ['marks']
}
},
size: {
width: 400,
},
axis: {
x: {
type: 'category'
}
},
bar: {
width: {
ratio: 0.5
}
}
});
I was getting the following output:
Here's the JSBin example: Bar Chart Example

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.

Creating a live web app

I have to make an application which dynamically updates data using Highcharts. That wasn't a big problem because they have a good tutorial. And the example works fine.
When I wan't to share this application across multiple device (using xampp), I have some problems. When I open the link to my webapp:
http://IP-adress/ENRGYMONITOR/index.html
The graph shows up, but the no data is displayed or updated. Here is the javascript I wrote:
var chart; // global
/**
* Request data from the server, add it to the graph and set a timeout to request again
*/
function requestData() {
$.ajax({
url: 'http://localhost/live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is longer than 20
// add the point
chart.series[0].addPoint(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 5000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
Can anyone let me know what the issue is?
Your $.ajax call is failing:
url: 'http://localhost/live-server-data.php'
"localhost" here would be the computer running the client (the web browser), not the server sending the data.
You should try to avoid an absolute URL. Modify it to just:
url: 'live-server-data.php'
assuming (this is important) that live-server-data.php is in the same directory as index.html

JSON, Codeigniter, Highcharts and AJAX

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"},

Categories

Resources