I have a Highchart object and a function to load the data:
graficaPropuestas = new Highcharts.Chart({
chart: {
height: 300,
renderTo: "graficaPropuestas",
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
events: {
load: recogerDatosInforme('propuesta', $(this))
}
}
})
And the function to load the data:
function recogerDatosInforme(tipo, gr) {
$.ajax({
url: '/Licencia/recogerDatosUsuariosSistema?tipo' + tipo,
datatype: "json",
success: function(data) {
gr.series[0].setData(data);
},
cache: false
});
}
I want to pass the graficaPropuestas object to the function so I can reuse the same function to load more graphs, however I cant get this to work. If I put in the function directly the graficaPropuestas object on the success: method it work well.
Any help would be appreciated.
If you will have only one instance of graficaPropuestas better and more efficient will be to use that solution:
var graficaPropuestas = new Highcharts.Chart( ...
function recogerDatosInforme(tipo) {
$.ajax({
url: '/Licencia/recogerDatosUsuariosSistema?tipo' + tipo,
datatype: "json",
success: function(data) {
graficaPropuestas.series[0].setData(data);
},
cache: false
});
}
I resolved it by this way:
The function to get the data:
function recogerDatosInforme(tipo, gr) {
$.ajax({
url: '/Informes/recogerDatosInforme?tipo=' + tipo,
datatype: "json",
success: function(data) {
gr.series[0].setData(data);
},
cache: false
});
}
Then I create the chart whithout the events method on the init:
graficaPropuestas = new Highcharts.Chart({
chart: {
height: 300,
renderTo: "graficaPropuestas",
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
}
})
And the I call the function with the graph object as an argument:
recogerDatosInforme('propuesta', graficaPropuestas)
So now I can make more chart objects and use the same function to get the data.
Related
I want to generate two lines into one chart, so i using join method in google chart.
I can retrieve data from SQL, but the script mentioned the data in data table is not array.
I tried to use $.parseJSON but still cannot plot to chart.
anyone can give me some hint?
Thank you in advance.
here is my script:
function drawMultiCavitiesChart() {
var options = {
title: 'Mulit Cavities vs Line',
width: 1800,
height: 700,
//bar: { groupWidth: "95%" },
//curveType: 'function',
//isStacked: true
pointSize: 8,
hAxis: { title: 'Date', format: 'M/d/yy' },
vAxis: { title: 'Total Cavities' },
//colors: ['blue'],
legend: { position: "bottom" }
};
var jsonData1 =
$.ajax({
type: "POST",
url: "Chart.aspx/GetMultiCavitiesData1",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (jsonData1) {
console.log(JSON.stringify(jsonData1));
},
});
//var data1 = google.visualization.arrayToDataTable(jsonData1);
//var data1 = google.visualization.arrayToDataTable($.parseJSON(jsonData1));
var jsonData2 =
$.ajax({
type: "POST",
url: "Chart.aspx/GetMultiCavitiesData2",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (jsonData2) {
console.log(JSON.stringify(jsonData2));
},
});
//var data2 = google.visualization.arrayToDataTable(jsonData2);
var data1 = google.visualization.arrayToDataTable($.parseJSON(jsonData1));
var data2 = google.visualization.arrayToDataTable($.parseJSON(jsonData2));
//var joinedData = new google.visualization.data.join(data1, data2, 'full', [[0, 0], [1, 1]], [2], [2]);
var joinedData = new google.visualization.data.join(data1, data2, 'full', [[0, 0]], [1], [1]);
var chart = new google.visualization.LineChart($("#divMultiCavitiesChart")[0]);
chart.draw(joinedData, options);
}
and the console:
$.ajax runs asynchronously.
which means the lines of code after the $.ajax call,
will run before the $.ajax call has finished.
so you're trying to create the data tables, before the data has been received.
you need to wait for the done callback, before continuing to the next step.
(you can also use success as in your post, but that is old and deprecated)
try something similar to the following...
function drawMultiCavitiesChart() {
var data1;
var data2;
var options = {
title: 'Mulit Cavities vs Line',
width: 1800,
height: 700,
//bar: { groupWidth: "95%" },
//curveType: 'function',
//isStacked: true
pointSize: 8,
hAxis: { title: 'Date', format: 'M/d/yy' },
vAxis: { title: 'Total Cavities' },
//colors: ['blue'],
legend: { position: "bottom" }
};
$.ajax({
type: "POST",
url: "Chart.aspx/GetMultiCavitiesData1",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
}).done(function (r1) {
data1 = google.visualization.arrayToDataTable(r1.d);
$.ajax({
type: "POST",
url: "Chart.aspx/GetMultiCavitiesData2",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
}).done(function (r2) {
data2 = google.visualization.arrayToDataTable(r2.d);
var joinedData = new google.visualization.data.join(data1, data2, 'full', [[0, 0]], [1], [1]);
var chart = new google.visualization.LineChart($("#divMultiCavitiesChart")[0]);
chart.draw(joinedData, options);
});
});
}
I have a Pie Chart and want to auto refresh it every 5 seconds. This is my code:
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var options = {
width: 900,
height: 500,
title: 'Partition des tickets',
legend: 'left',
is3D: true
};
$.ajax({
type: "POST",
url: "Home.aspx/GetPieChartData",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = google.visualization.arrayToDataTable(r.d);
var chart = new google.visualization.PieChart($("#chart_Pie")[0]);
chart.draw(data, options);
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
You can use setTimeout to run the script every 5 secs. I also added an isDrawing flag so that you don't trigger the function again while it's drawing.
<script type="text/javascript">
var isDrawing = false;
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(() => {
// draw the first time
drawChart();
// start automatic refresh
setTimeout(() => {
if (!isDrawing) {
drawChart();
}
}, 5000);
});
function drawChart() {
isDrawing = true;
var options = {
width: 900,
height: 500,
title: "Partition des tickets",
legend: "left",
is3D: true
};
$.ajax({
type: "POST",
url: "Home.aspx/GetPieChartData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(r) {
var data = google.visualization.arrayToDataTable(r.d);
var chart = new google.visualization.PieChart($("#chart_Pie")[0]);
chart.draw(data, options);
isDrawing = false;
},
failure: function(r) {
alert(r.d);
isDrawing = false;
},
error: function(r) {
alert(r.d);
isDrawing = false;
}
});
}
</script>
i fixed it , if any one want to update any google chart dynamicly you just need to add update() function like you see
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var options = {
width: 900,
height: 500,
title: 'Partition des tickets',
legend: 'left',
is3D: true,
};
$.ajax({
type: "POST",
url: "Home.aspx/GetPieChartData",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = google.visualization.arrayToDataTable(r.d);
var chart = new google.visualization.PieChart($("#chart_Pie")[0]);
chart.draw(data, options);
updateChart();
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
function updateChart() {
$.ajax({
type: "POST",
url: "Home.aspx/GetPieChartData",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = google.visualization.arrayToDataTable(r.d);
var chart = new google.visualization.PieChart($("#chart_Pie")[0]);
chart.draw(data, options);
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
setTimeout(function () { updateChart() }, 1000);
};
}
</script>
I've successfully managed to create a line chart by retrieving the dataset from an ajax call when the line chart only has a single line.
I now need to create a line chart with 2 lines, but I can't get it working.
My ajax return data is built in php. This is the code:
$returnData['line'] = array(
'type' => 'line',
'title' => 'Title',
'labels' => array('Jan','Feb'),
'datasets' => array(
array(
'data' => array(0,50),
'borderColor' => "#f7464a",
'label' => "Label 1",
'fill' => false
),
array(
'data' => array(10,20),
'borderColor' => "#8e5ea2",
'label' => "Label 2",
'fill' => true
)
)
);
echo json_encode($returnData);
My jQuery ajax call is:
$.ajax({
url: "https://example.com/chart_data",
type: "POST",
dataType: 'json',
success: function(rtnData) {
$.each(rtnData, function(dataType, data) {
console.log(data.datasets);
var ctx = document.getElementById("linechart").getContext("2d");
var config = {
type: data.type,
data: {
datasets: [data.datasets],
labels: data.labels
},
options: {
responsive: true,
title: {
display: true,
text: data.title
}
}
};
window.myPie = new Chart(ctx, config);
});
},
error: function(rtnData) {
alert('error' + rtnData);
}
});
The data looks good when I view what has been logged in the console, so I don't know why this isn't working.
All I get is the chart, but no lines.
I'm looking for a future-proofed solution where I can add as many lines as needed to the chart just by amending the php code, without then having to change the jQuery too.
I've spotted my mistake in case anybody else runs into this....the square brackets need to be removed from the 'datasets' parameter:
$.ajax({
url: "https://example.com/chart_data",
type: "POST",
dataType: 'json',
success: function(rtnData) {
$.each(rtnData, function(dataType, data) {
console.log(data.datasets);
var ctx = document.getElementById("linechart").getContext("2d");
var config = {
type: data.type,
data: {
datasets: data.datasets,
labels: data.labels
},
options: {
responsive: true,
title: {
display: true,
text: data.title
}
}
};
window.myPie = new Chart(ctx, config);
});
},
error: function(rtnData) {
alert('error' + rtnData);
}
});
I am trying to hide the labels in my pie chart. I think the correct word is labels? But I could be wrong. Basically I have a pie chart That displays some data, outside of the pie chart it has a label with a color cube and a name next to it displaying what each color stands for, I would like to get rid of that, because on hover I show the same data and it takes up some valuable real estate I would like to use. Here is my Javascript code:
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var options = {
title: '',
is3D: true
};
$.ajax({
type: "POST",
url: "myPage.aspx/GetChartData",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
//console.log(JSON.stringify(r))
var data = google.visualization.arrayToDataTable(r.d);
var chart = new google.visualization.PieChart($("#chart")[0]);
var formatter = new google.visualization.NumberFormat(
{ negativeColor: 'red', negativeParens: true, pattern: '$###,###.##' });
formatter.format(data, 1);
chart.draw(data, options);
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
Google charts Visualization, killing legend:
legend: {position: 'none'}
-- this will kill the legend in Google Charts.
Also, the JS to do it:
http://jsfiddle.net/api/post/library/pure/
legend: 'none'
So, ultimately this should do it for you:
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var options = {
title: '',
is3D: true,
legend: none,
};
$.ajax({
type: "POST",
url: "myPage.aspx/GetChartData",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
//console.log(JSON.stringify(r))
var data = google.visualization.arrayToDataTable(r.d);
var chart = new google.visualization.PieChart($("#chart")[0]);
var formatter = new google.visualization.NumberFormat(
{ negativeColor: 'red', negativeParens: true, pattern: '$###,###.##' });
formatter.format(data, 1);
chart.draw(data, options);
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
I am working on the highchart.I came across a problem where the categories data and series data which I am loading dynamically is not showing up. Here is my code.
function loadChart() {
var categories = [];
var trend_series = [];
$.ajax({
type:'POST',
url : '/trends.php',
dataType: 'json',
async : 'false',
data: { date: d, item_name: item },
success: function( data ) {
$.each( data, function( key, val ) {
categories.push( key );
trend_series.push( parseFloat( val ) );
});
},
error: function( data ) {
//alert(data['responseText']);
}
});
$( function () {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line'
},
xAxis: {
categories: {}
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
});
chart.xAxis[0].setCategories( categories );
chart.addSeries({
name: 'App Summary',
data: trend_series
});
});
}
I am calling the loadChart() from another file.
One of the main problem which I notice that the categories and trend_series (these are arrays )is empty inside the highchart function . But it is not empty inside the ajax function call. How can I pass those values to highchart function or is there any other method to achieve this.
You're modifying the categories and the data but the chart has no way to be notified of that.
You need to do categories.push() and then redo chart.xAxis[0].setCategories(categories,true) again, and same with the data, chart.series[0].setData(trend_series,true) in your success function in the ajax call.
The true option triggers the chart.redraw()
I end up with this solution even though it is bit wierd,
I moved the enitre highchart function to another function. On ajax success function I am calling the next function renderChart() . The code is as follows.
function loadChart() {
categories = [];
trend_series = [];
$.ajax({
type:'POST',
url : '/trends.php',
dataType: 'json',
async : 'false',
data: { date: d, item_name: item },
success: function( data ) {
$.each( data, function( key, val ) {
categories.push( key );
trend_series.push( parseFloat( val ) );
});
renderChart(categories,trend_series);
},
error: function( data ) {
//alert(data['responseText']);
}
});
}
To load highchart
function renderChart(categories,trend_series){
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line'
},
xAxis: {
categories: {}
},
series: {}
}]
});
chart.xAxis[0].setCategories( categories );
chart.addSeries({
name: 'App Summary',
data: trend_series
});
}
Will be better if you use
$.ajax({
type:'POST',
url : '/trends.php',
dataType: 'json',
async : 'false',
data: { date: d, item_name: item },
success: function( data ) {
var options = {
chart: {
renderTo: 'container',
type: 'line'
},
xAxis: {
categories: []
},
series:{
data:[]
}
}
$.each( data, function( key, val ) {
options.xAxis.categories.push(key);
options.series.data.push( parseFloat( val ) );
});
var chart = new Highcharts.Chart(options);
},
error: function( data ) {
//alert(data['responseText']);
}
});