Highchart, dynamically change the chart type - ajax

html
<div id="top10_" style="float:left">
<strong>Top10:</strong>
<select id="top10_update">
<option value="typ">Typ</option>
<option value="kategoria">Kategoria</option>
<option value="typ2 selected="selected" >Typ2</option>
<option value="usluga">usługa</option>
</select>
<img id="set_column" src="static/images/chart-bar-icon.png" width="20" />
<img id="set_pie" src="static/images/chart-pie-icon.png" width="20" />
<img id="set_area" src="static/images/Chart-Graph-Ascending-icon.png" width="20" />
<img id="set_line" src="static/images/chart_curve.png" width="20" />
</div>
<div id="top10" style="min-width: 400px; height: 400px; margin: 0 auto;"></div>
js
$('#set_column').click(function() {
var chart = $(this).parent('div').attr('id');
chart = chart.replace('_','');
$('#'+chart).highcharts().series[0].update({ type: "column"});
});
$('#set_pie').click(function() {
var chart = $(this).parent('div').attr('id');
chart = chart.replace('_','');
$('#'+chart).highcharts().series[0].update({ type: "pie"});
});
$('#set_area').click(function() {
var chart = $(this).parent('div').attr('id');
chart = chart.replace('_','');
$('#'+chart).highcharts().series[0].update({ type: "area"});
});
$('#set_line').click(function() {
var chart = $(this).parent('div').attr('id');
chart = chart.replace('_','');
$('#'+chart).highcharts().series[0].update({ type: "line"});
});
and chart
$('#top10').highcharts({
chart: {
type: 'column',
margin: [ 50, 50, 100, 80]
},
title: {
text: 'TOP10'
},
subtitle: {
text: ' '
},
credits: {
enabled: false
},
xAxis: {
categories: [],
labels: {
rotation: -45,
align: 'right',
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
},
yAxis: {
min: 0,
title: {
text: 'Ilość'
}
},
legend: {
enabled: false
},
tooltip: {
formatter: function() {
return '<b>'+ this.x +'</b><br/>'+
'Ilość: '+ this.y;
}
},
series: [{
name: 'Ilość, TOP10',
data: [],
dataLabels: {
enabled: true,
rotation: -90,
color: '#FFFFFF',
align: 'right',
x: 4,
y: 10,
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
}]
});
as you can see it has empty data because data is loaded dynamically with ajax
function ajax_update(date) {
$.ajax({
url: "index.php/ajax",
async: false,
method: 'post',
dataType: "json",
data: {date:date},
beforeSend: function(){
$('#loading').show();
$('#top10').highcharts().showLoading();
},
success: function(dane) {
$('#top10').highcharts().xAxis[0].setCategories(dane.top10.xlabel, false);
$('#top10').highcharts().series[0].setData(dane.top10.data);
$('#top10').highcharts().setTitle(null, { text: 'Dane za: '+date.replace('^', ' - ') });
$('#top10').highcharts().hideLoading();
$('#loading').hide();
},
error: function (dane) {
alert( dane.responseText );
}
});
}
the problem is that when I click on the icon to change the type of chart data on chart disappear and when update it using the above-mentioned function it shows again with a modified type
live, working example is here: http://jsfiddle.net/zqvNq/1/
but as i said, i have empty data and append it to chart with json

here's example how i fix this:
var global_highcharts = new Object();
function ajax_update_chart(level, date, co) {
$.ajax({
url: "index.php/ajax/"+co,
async: false,
method: 'post',
dataType: "json",
data: {date:date, level:level},
beforeSend: function(){
$('#loading').show();
$('#'+co.substr(7)).highcharts().showLoading();
},
success: function(dane) {
$.each(dane, function(i) {
global_highcharts[i+'Cat'] = this.categories;
global_highcharts[i+'Dat'] = this.data;
$('#'+i).highcharts().xAxis[0].setCategories( this.categories, false );
$('#'+i).highcharts().series[0].setData( this.data );
$('#'+i).highcharts().hideLoading();
});
//ustawiamy domyślne wartości które w main.php mają ustawione selected aby nie mylić ludzi na stronie
$('#loading').hide();
//console.log( global_highcharts );
},
error: function (dane) {
alert( dane.responseText );
}
});
}
$.each(['line', 'column', 'spline', 'area', 'areaspline', 'scatter', 'pie'], function (i, type) {
$('#' + type).click(function () {
var chartaz = $('#top10').highcharts();
chartaz.series[0].update({
type: type
});
$('#top10').highcharts().xAxis[0].setCategories( global_highcharts.top10Cat , false);
$('#top10').highcharts().series[0].setData( global_highcharts.top10Dat );
});
});
just appending data once againt

Related

kendo tooltip is shown only after second 'hover' event

I use kendo grid and want to show kendo tooltip for icon in header cells.
I have the following code:
<div id="grid"></div>
<script>
$(document).ready(function () {
var grid = $("#grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("List", "i3screenResult"))",
type: "POST",
dataType: "json",
data: function () {
var data = {
};
addAntiForgeryToken(data);
return data;
}
}
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},
},
dataBinding: function (e) {
$('.questionmark').on("hover", function () {
var tooltip = $(this).kendoTooltip({
content: $(this).attr('tooltip'),
width: 120,
position: "top",
animation: {
open: {
effects: "zoom",
duration: 150
}
}
}).data("kendoTooltip");
});
},
scrollable: false,
columns: [
{
field: "BackgroundReportAccount",
headerTemplate: "#T("DrugConsortium.i3screen.Fields.BackgroundReportAccount") <img src='/images/question-mark-icon.png' class='questionmark' tooltip='#T("DrugConsortium.i3screen.Fields.BackgroundReportAccount.Details")' />",
width: 150
},
{
field: "ProviderReferenceId",
headerTemplate: "#T("DrugConsortium.i3screen.Fields.ProviderReferenceId") <img src='/images/question-mark-icon.png' class='questionmark' tooltip='#T("DrugConsortium.i3screen.Fields.ProviderReferenceId.Details")' />",
width: 150
},
//....
]
});
});
</script>
It works, but only since second hover event for img.
Why so and how to fix?
Try this AFTER grid initialization:
$('#grid').kendoTooltip({
content: function(e) {
return $(e.target).attr('tooltip');
},
filter: 'img.questionmark',
width: 120,
position: "top",
animation: {
open: {
effects: "zoom",
duration: 150
}
}
});
Also, you should change the attribute name from tooltip to data-tooltip since tooltip is not a standard HTML attribute. Then you can get it's value with $(e.target).data('tooltip');
Demo

Kendo batch editing with entire grid edit mode

I have implemented kendo grid batch editing feature to my application. I am able to save the changes by the default functionality provided by kendo. Here is the same code I have implemented in my project:
<!DOCTYPE html>
<html>
<head>
<base href="https://demos.telerik.com/kendo-ui/grid/editing">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.common.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.flat.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.flat.mobile.min.css" />
<script src="https://kendo.cdn.telerik.com/2017.3.1026/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.3.1026/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "https://demos.telerik.com/kendo-ui/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true } },
UnitPrice: { type: "number", validation: { required: true, min: 1} },
Discontinued: { type: "boolean" },
UnitsInStock: { type: "number", validation: { min: 0, required: true } }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
navigatable: true,
pageable: true,
height: 550,
toolbar: ["create", "save", "cancel"],
columns: [
"ProductName",
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: 120 },
{ field: "UnitsInStock", title: "Units In Stock", width: 120 },
{ field: "Discontinued", width: 120, editor: customBoolEditor },
{ command: "destroy", title: " ", width: 150 }],
editable: true
});
});
function customBoolEditor(container, options) {
var guid = kendo.guid();
$('<input class="k-checkbox" id="' + guid + '" type="checkbox" name="Discontinued" data-type="boolean" data-bind="checked:Discontinued">').appendTo(container);
$('<label class="k-checkbox-label" for="' + guid + '">​</label>').appendTo(container);
}
</script>
</div>
</body>
</html>
I need a feature to show the entire grid in edit mode have all the editable column with edit templates. I tried to add same client template as editor template but the behavior is not as expected. Is there any way to show both client template and editor template with a common template?
For e.g.
In the above example, I need Unit Price with numeric textbox present on all the rows. Not only when I click to it.
Here has an example;
$("#grid").kendoGrid({
dataSource: {
schema: {
model: {
id: "id",
fields: {
id: { editable: false }
}
}
},
change: function() {
$("textarea").val(
kendo.stringify(this.view())
);
},
data: [
{ id:1, age: 30, name: "John Doe" }
]
},
columns: [
{ field: "id", width: 50 },
{ field: "age", template: "<input data-bind='value: age' data-role='numerictextbox'>" },
{ field: "name", template:"<input data-bind='value: name' >" }
],
dataBound: function() {
var rows = this.tbody.children();
var dataItems = this.dataSource.view();
for (var i = 0; i < dataItems.length; i++) {
kendo.bind(rows[i], dataItems[i]);
}
}
});
http://jsbin.com/ApoFobA/2/edit?html,js,output

Populate three highchart graphics with one ajax call

I am trying to figure out how to combine 3 ajax call into 1 but so far I didn't find out the correct way to do it. I have the following three highcharts:
chart1 = new Highcharts.Chart({
chart: {
height: 155,
renderTo: 'chart1_div',
defaultSeriesType: 'spline',
events: {
load: GetData1(date)
}
},
plotOptions: {
series: {
fillOpacity: 0.1
}
},
xAxis: {
categories: c,
labels: {
staggerLines: 2
}
},
yAxis: {
gridLineColor: "#ffffcc",
title: {
text: ''
},
labels: {
x: 15,
y: 15,
style: {
color: "#999999",
//fontWeight: "bold",
fontSize: "10px"
}
},
},
series: [{
name: 'Chart1',
color: "#6bd9ec", //37f312
data: chart1_data
}]
});
chart2 = new Highcharts.Chart({
chart: {
height: 155,
renderTo: 'chart2_div',
defaultSeriesType: 'spline',
events: {
load: GetData2(date)
}
},
plotOptions: {
series: {
fillOpacity: 0.1
}
},
xAxis: {
categories: c,
labels: {
staggerLines: 2
}
},
yAxis: {
gridLineColor: "#ffffcc",
title: {
text: ''
},
labels: {
x: 15,
y: 15,
style: {
color: "#999999",
//fontWeight: "bold",
fontSize: "10px"
}
},
},
series: [{
name: 'Chart2',
color: "#6bd9ec", //37f312
data: chart2_data
}]
});
chart3 = new Highcharts.Chart({
chart: {
height: 155,
renderTo: 'chart3_div',
defaultSeriesType: 'spline',
events: {
load: GetData3(date)
}
},
plotOptions: {
series: {
fillOpacity: 0.1
}
},
xAxis: {
categories: c,
labels: {
staggerLines: 2
}
},
yAxis: {
gridLineColor: "#ffffcc",
title: {
text: ''
},
labels: {
x: 15,
y: 15,
style: {
color: "#999999",
//fontWeight: "bold",
fontSize: "10px"
}
},
},
series: [{
name: 'Chart3',
color: "#6bd9ec", //37f312
data: chart3_data
}]
});
At the moment I am making three different ajax calls:
function GetData1(date) {
$.ajax({
url: '/GetAjaxCall',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ date: date }),
success: function (f) {
var cat= [];
var ser= [];
$.each(f.d, function (i, e) {
cat.push(e.date);
ser.push(parseInt(e.val1));
});
chart1_div.xAxis[0].setCategories(cat);
chart1_div.series[0].setData(ser);
},
error: function (e) {
alert(e.statusText);
},
cache: false
});
}
function GetData2(date) {
$.ajax({
url: '/GetAjaxCall',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ date: date }),
success: function (f) {
var cat= [];
var ser= [];
$.each(f.d, function (i, e) {
cat.push(e.date);
ser.push(parseInt(e.val2));
});
chart2_div.xAxis[0].setCategories(cat);
chart2_div.series[0].setData(ser);
},
error: function (e) {
alert(e.statusText);
},
cache: false
});
}
function GetData3(date) {
$.ajax({
url: '/GetAjaxCall',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ date: date }),
success: function (f) {
var cat= [];
var ser= [];
$.each(f.d, function (i, e) {
cat.push(e.date);
ser.push(parseInt(e.val3));
});
chart3_div.xAxis[0].setCategories(cat);
chart3_div.series[0].setData(ser);
},
error: function (e) {
alert(e.statusText);
},
cache: false
});
}
As you can see, I am right now making the same ajax call 3 times just to be able to populate the 3 charts differently. Does anyone know how could I generate exactly the same 3 charts but only make 1 ajax call? Thanks a lot
Something like:
function GetDataAll(date) {
$.ajax({
url: '/GetAjaxCall',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ date: date }),
success: function (f) {
var cat1= [];
var ser1= [];
var cat2= [];
var ser2= [];
var cat3= [];
var ser3= [];
$.each(f.d, function (i, e) {
cat1.push(e.date);
ser1.push(parseInt(e.val1));
});
chart1_div.xAxis[0].setCategories(cat1);
chart1_div.series[0].setData(ser1);
chart2_div.xAxis[0].setCategories(cat2);
chart2_div.series[0].setData(ser2);
chart3_div.xAxis[0].setCategories(cat3);
chart3_div.series[0].setData(ser3);
},
error: function (e) {
alert(e.statusText);
},
cache: false
});
}
Under the load event I could call GetData1(date) for the 3 charts but this way I will be hitting the ajax call 3 times. I am probably doing this the wrong way and must be a more efficient way. I will appreciate any thoughts, thank you so much
EDITED - LATEST UPDATE THAT WORKS BASED ON #WERGELD HELP
var chart1_options = {
chart: {
renderTo: 'chart1_div',
xAxis: {
categories: []
},
series: [{
name: 'Chart1',
color: "#6bd9ec"
}]
};
var chart2_options = {
chart: {
renderTo: 'chart2_div',
xAxis: {
categories: []
},
series: [{
name: 'Chart2',
color: "#6bd9ec"
}]
};
var chart3_options = {
chart: {
renderTo: 'chart3_div',
xAxis: {
categories: []
},
series: [{
name: 'Chart3',
color: "#6bd9ec"
}]
};
function GetDataAll(date) {
$ajax({..
chart1_options.xAxis.categories = cat1;
chart1_options.series[0].data = ser1;
chart2_options.xAxis.categories = cat2;
chart2_options.series[0].data = ser2;
chart3_options.xAxis.categories = cat3;
chart3_options.series[0].data = ser3;
var chart1 = new Highcharts.Chart(Highcharts.merge(options, chart1_options));
var chart2 = new Highcharts.Chart(Highcharts.merge(options, chart2_options));
var chart3 = new Highcharts.Chart(Highcharts.merge(options, chart3_options));
});
}
Here is some psuedo code to get you going. What you need to do is setup a chart option object that contains all the constant items among your charts:
var options = {
chart: {
height: 155,
defaultSeriesType: 'spline'
},
plotOptions: {
series: {
fillOpacity: 0.1
}
},
xAxis: {
categories: c,
labels: {
staggerLines: 2
}
},
yAxis: {
gridLineColor: "#ffffcc",
title: {
text: ''
},
labels: {
x: 15,
y: 15,
style: {
color: "#999999",
//fontWeight: "bold",
fontSize: "10px"
}
},
}
};
Next you do your ajax call and assign your series' data and title (and any other items) and create an object for each chart you want to create:
var chartOptions1 = {
chart: { renderTo: 'container1' },
series: []
};
var chartOptions2 = {
chart: { renderTo: 'container1' },
series: []
};
Next you do your code to get the chart data/name/etc that you want to have for each chart which I will not go into here. The next step is to then create your chart from the merged options:
var chart1 = new Highcharts.Chart(Highcharts.merge(options, chartOptions1));
var chart2 = new Highcharts.Chart(Highcharts.merge(options, chartOptions2));
This should do it. Again, it is psuedocode but you get the idea. Global options + merge are you friends. Full psuedocode here.

highcharts - drilldown: does not workn with AJAX

I have a chart below that does not work with AJAX request.
function ajaxGraficoBarraUnidade() {
var strSeries = "";
var strDrilldown = "";
$.ajax({
type: "POST",
data: window.formData + '&strMundo=' + "<?php echo ($strMundo); ?>" + '&strGraph=Unidade',
dataType: "json",
url: "ajaxBlitzCarregamentoGrafico.php",
beforeSend: function () {
},
success: function (strRetorno) {
strSeries = strRetorno.geos;
strDrilldown = strRetorno.unidades;
carregaGraficoBarraUnidade(strSeries, strDrilldown);
},
error: function (txt) {
}
});
}
function carregaGraficoBarraUnidade(strSeries, strDrilldown) {
$('#divGraficoBarraUnidade').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Browser market shares. January, 2015 to May, 2015'
},
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: strSeries,
drilldown: {
series: strDrilldown
}
});
</code>
I have a return equal to ajax below:
{'geos':[{'name': 'Regionais','data': [{'name':'Geo CO','y':1.59,'drilldown':'Geo CO'},{'name':'Geo MG/ES','y':4.41,'drilldown':'Geo MG/ES'},{'name':'Geo NE','y':3.35,'drilldown':'Geo NE'},{'name':'Geo NO','y':1.96,'drilldown':'Geo NO'},{'name':'Geo PR/SPI','y':0.10,'drilldown':'Geo PR/SPI'},{'name':'Geo RJ','y':1.81,'drilldown':'Geo RJ'},{'name':'Geo RS/SC','y':0.75,'drilldown':'Geo RS/SC'},{'name':'Geo SPC','y':0.33,'drilldown':'Geo SPC'}]}], 'unidades':[{'name':'Geo CO','id':'Geo CO','data': [['CDC Araguaina',1.30],['CDC Catalao',0.01],['CDC Formosa',4.70],['CDC Porto Velho',0.29],['CDC Rio Branco',0.00],['CDC Rio Verde',0.12],['CDC Rondonopolis',5.15],['CDC Tangara',0.51],['CDD Brasilia',0.06],['CDD Brasilia Int',2.67],['CDD Caceres',0.05],['CDD Campo Gde',0.00],['CDD Cuiaba Int',0.03],['CDD Goiania Int',0.00],['CDD Itumbiara',38.19],['CDD Manaus',0.43]]},{'name':'Geo MG/ES','id':'Geo MG/ES','data': [['CDD Alfenas',0.02],['CDD Cachoeiro',0.28],['CDD Ipatinga',0.03],['CDD João Monlevade DDC',0.00],['CDD Minas Int',0.77],['CDD Poços de Caldas',0.91],['CDD Pouso Alegre',0.17],['CDD Uberaba',0.08],['CDD Uberlandia',0.07],['CDD Vitoria',25.62],['CDL AS Minas',0.01],['CDL Santa Luzia',2.70]]},{'name':'Geo NE','id':'Geo NE','data': [['CDC Arapiraca',0.12],['CDC Lapa',0.32],['CDD Aracaju',0.05],['CDD Caruaru',8.05],['CDD F. de Santana',0.17],['CDD Guanambi',0.01],['CDD Ilheus',0.03],['CDD Maceio',0.06],['CDD Olinda',0.16],['CDD Rib. Pombal',0.04],['CDD Salvador',0.17],['CDD Vit. da Conquista',0.06],['CDL Cabo',1.33],['CDL Jequie',0.06]]},{'name':'Geo NO','id':'Geo NO','data': [['CDD Aracati',0.02],['CDD Balsas',0.08],['CDD Belem',0.02],['CDD Campina Grande',0.03],['CDD Fortaleza',0.03],['CDD Imperatriz',0.02],['CDD Joao Pessoa Int',5.86],['CDD Maranhao Int ',12.72],['CDD Natal Int',0.02],['CDD Sul Maranhão',0.03],['CDL Ceara',0.37]]},{'name':'Geo PR/SPI','id':'Geo PR/SPI','data': [['CDC Beltrao',0.00],['CDD Agudos Int',0.12],['CDD Araçatuba',0.07],['CDD Araraquara',0.02],['CDD Bebedouro',0.09],['CDD Curitiba',0.00],['CDD Jaú',3.19],['CDD Londrina',0.00],['CDD Mogi Mirim',0.04],['CDD Ponta Grossa',0.37],['CDD Presidente Prudente',0.05],['CDD Rib. Preto',0.04],['CDL Paranagua',0.02]]},{'name':'Geo RJ','id':'Geo RJ','data': [['CDD Campos',1.18],['CDD Jacarepagua',1.65],['CDD Niteroi',0.02],['CDD Nova Friburgo',0.01],['CDD Nova Iguacu',0.02],['CDD Petropolis',0.00],['CDD RJ Campo Gde Int',3.77],['CDD S. Cristovao',0.81],['CDL Itaperuna',0.14]]},{'name':'Geo RS/SC','id':'Geo RS/SC','data': [['CDD Blumenau',0.07],['CDD Camboriu',0.11],['CDD Caxias do Sul',0.07],['CDD Florianopolis',0.12],['CDD Pelotas',0.04],['CDD Porto Alegre',1.06],['CDD S. Cruz Sul',0.02],['CDD Santa Maria',0.45],['CDD Sapucaia Int',2.66]]},{'name':'Geo SPC','id':'Geo SPC','data': [['CDD Campinas',0.12],['CDD Diadema',0.72],['CDD Guarulhos',0.23],['CDD Jundiai',1.04],['CDD Litoral SP',0.05],['CDD Mooca',1.05],['CDD Norte',0.10],['CDD Oeste',0.04],['CDD Praia Grande',0.06],['CDD São José dos Campos',0.54],['CDD Sul SP',0.00],['CDD Taubaté',0.82],['CDD Votorantin',0.77]]}]}
It does not recognize the values passed in SERIES. I do not think the error. Does anyone know what might be happening? Tanks!
What might be happening is your data is getting loaded after the chart is created, so I've changed the format to be as shown in the Highcharts documentation, but tried not to change to much otherwise.
Highcharts documentation on working with data
See a plunkr demo with your chart working with available data
The data is hosted on myjson.com as JSON, so I changed the POST to a GET request.
Here is the key HTML code:
<script src="https://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<div id="divGraficoBarraUnidade" style="width:100%; height:400px;"></div>
This is the Javascript / jQuery code:
$(function () {
$(document).ready(function() {
var options = {
chart: {
renderTo: 'divGraficoBarraUnidade',
type: 'column'
},
title: {
text: 'Browser market shares. January, 2015 to May, 2015'
},
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: {},
drilldown: {
series: {}
}
};
function ajaxGraficoBarraUnidade() {
$.ajax({
type: "GET",
data: window.formData + '&strMundo=' + "<?php echo ($strMundo); ?>" + '&strGraph=Unidade',
dataType: "json",
url: "https://api.myjson.com/bins/42c59",
beforeSend: function () {
},
success: function (strRetorno) {
options.series = strRetorno.geos;
options.drilldown.series = strRetorno.unidades;
var chart = new Highcharts.Chart(options);
console.log('options', options)
},
error: function (txt) {
// Report errors here...
}
});
}
ajaxGraficoBarraUnidade();
});
});

HighCharts load data via ajax

I have been encountering issues for the past few days with ajaxing in some sample json data from an api to populate a chart using the Highcharts library.
I tried to chart.series[0].data = json and similar stuff in my ajax callback but nothing works.
my json is an array of data for each day in the month.
"{"month_mentions_graphic":[521,49,81,0,101,0,0,0,21,3071,0,0,0,0,0,1479,6124,2409,2608,0,0,3457,2057,2580,5876,4638,0,0,3337,3479,430]}"
Here's my code:
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25,
events: {
load: requestData
}
},
title: {
text: 'Menções Mensais',
x: -20 //center
},
xAxis: {
categories: [1,2,3,4,5]
},
yAxis: {
title: {
text: 'Menções'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [
{
name: 'mentions',
data: []
}
]
});
});
function requestData() {
$.ajax({
url: 'api/v1/dashboard/month_mention_graphic',
type: "GET",
dataType: "json",
data : {username : "demo"},
success: function(data) {
chart.series[0].data = data;
},
cache: false
});
}
Call chart.addSeries to add the whole series in one go instead of adding just the point array to the initial empty series:
function requestData() {
$.ajax({
url: 'api/v1/dashboard/month_mention_graphic',
type: "GET",
dataType: "json",
data : {username : "demo"},
success: function(data) {
chart.addSeries({
name: "mentions",
data: data.month_mentions_graphic
});
},
cache: false
});
}

Resources