highcharts line graph with ajax - ajax

I would like to implement a simple line graph with ajax in which only two points
x will be the hours and y will be the count of calls.
CODE :
<script>
function getData() {
$.ajax({
type:'POST',
url: "http://localhost/demo_chart/test.php",
dataType: 'JSON',
success: function(response_data) {
new_data = $.map(response_data, function(i){
return {x: i['date'],y: i['count']};
});
$('#container').highcharts({
chart: {
renderTo: 'container',
type: 'line'
},
title: {
text: 'Count vs. Time'
},
xAxis: {
title: {
text: 'Time'
},
type: 'Time',
},
yAxis: {
title: {
text: 'Count'
}
},
series: [{
name: 'Test',
data: new_data
}]
});
}
})
}
$(document).ready(function () {
getData();
})
</script>
Output of http://localhost/demo_chart/test.php is same as below :
{"date":["13:00:00","13:00:01","13:00:02","13:00:03","13:00:04"],"count":["1","2","3","4","2"]}
But still graph is not generating. So i would like to know what is the problem here.
Anyone like to share some hint which can resolve this problem ?
Expected output is :
X- axis : show all date
Y-axis : show count

You need to correct your mapping function, for example:
var response = {
"date": ["13:00:00", "13:00:01", "13:00:02", "13:00:03", "13:00:04"],
"count": ["1", "2", "3", "4", "2"]
};
new_data = $.map(response.date, function(el, index) {
return {
name: el,
y: parseInt(response['count'][index])
};
});
Additionally, with that data structure, I recommend you to use category axis type.
xAxis: {
...,
type: 'category'
}
Live demo: http://jsfiddle.net/BlackLabel/ptx6fy2q/
API Reference: https://api.highcharts.com/highcharts/xAxis.type

Related

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

Show dynamic array data in column of c3js graph

How to show array data in column of a graph, that will have any number of values in it
I tried below code, and it is not working:
$http.get(getUrl('api/Report/GetDepartmentTargetData') + "?year="+ $scope.selectYear + "&ideaPerUser=" + $scope.ideaPerAssociate).then(function (response) {
$scope.deptChart = c3.generate({
data: {
bindto: '#chart',
x: 'x',
columns: [
['x', response.data.XAxis],
['Achievement', response.data.Data]
],
type: 'bar',
},
zoom: {
enabled: true
},
axis: {
x: {
type: 'categorized',
}
},
});
}, function (errors) {
});
response of the url that is being called from the angular js, it can be of any length:
<DepartmentTargetModel>
<Data>
<d2p1:string>0%</d2p1:string>
<d2p1:string>0%</d2p1:string>
<d2p1:string>100%</d2p1:string>
</Data>
<TargetLine>
<d2p1:string>72%</d2p1:string>
<d2p1:string>72%</d2p1:string>
<d2p1:string>72%</d2p1:string>
</TargetLine>
<XAxis>
<d2p1:string>RBEI/BSW2</d2p1:string>
<d2p1:string>RBVH/ETI1</d2p1:string>
<d2p1:string>BetP/BPS</d2p1:string>
</XAxis>
</DepartmentTargetModel>

c3.js: Remove categories from x-axis

I've spent a lot of time with c3's documentation and examples, but have not been able to find a a way to unload or hide a category from a chart using API functions. Removing lines or bars is easy, but removing x-axis categories is proving more challenging. Here is a streamlined version of my chart.
var genderChart = c3.generate({
bindto: '#chart-gender',
data: {
json: [
{
Disease:"Mumps",
"Female":231,
"Male":198
},
Disease:"Tuberculosis",
"Female":18,
"Male":197
}
],
type: 'bar',
keys: {
x: "Disease",
value: ["Female","Male"]
},
selection: {
enabled: true,
grouped: true
},
},
axis: {
x: {
type: 'category',
}
},
});
I would like to dynamically show and hide (load and unload) diseases. For instance, I would like to be able to toggle Tuberculosis on and off. My actual chart has a number of other diseases. If I structured the data such that the diseases were bars and gender was on the x-axis, this would be easy. However, that is not comparison I wish to show with this chart. Is this possible with c3? How do I select all of the values with a given x value (disease) and then unload those data points? I appreciate any insight.
I would build up the json data object and then re-render the chart.
Here's an example:
var data = [{
Disease: "Mumps",
Female: 231,
Male: 198
}, {
Disease: "Tuberculosis",
Female: 18,
Male: 197
}];
$("button").click(function () {
Render();
});
Render()
function Render() {
var selectedData = [];
if ($("#mumps").prop("checked")) selectedData.push(data[0]);
if ($("#tb").prop("checked")) selectedData.push(data[1]);
var genderChart = c3.generate({
data: {
json: selectedData,
type: 'bar',
keys: {
x: "Disease",
value: ["Female", "Male"]
},
selection: {
enabled: true,
grouped: true
},
},
axis: {
x: {
type: 'category',
}
},
});
}
Here's the code in a fiddle:
http://jsfiddle.net/ot19Lyt8/14/

ExtJS toolbar load items

I need to load items (menu) via ajax but do not understand how...
trying to do like this:
var tb = Ext.create('Ext.toolbar.Toolbar', {
renderTo: 'top-menu',
autoLoad: {
url: '/index/tullbar',
renderer: 'component',
params: {
userId: 1
}
},
layout: {
overflowHandler: 'Menu'
}
});
});
response:
[
{
"text": "test",
"menu": {
"text": "asdf",
"handler":"handleAction.createDelegate(window)"
}
}
]
but handler is not working.
Can anybody give the working example.
I haven't used element loader before so I would make a wild guess that you should specify a renderer function according to http://docs.sencha.com/ext-js/4-0/#/api/-cfg-renderer:
var tb = Ext.create('Ext.toolbar.Toolbar', {
renderTo: 'top-menu',
autoLoad: {
url: '/index/tullbar',
renderer: function(loader, response) {
var menuItems = Ext.decode(response.responseText);
tb.items.add(menuItems);
},
params: {
userId: 1
}
},
layout: {
overflowHandler: 'Menu'
}
});

Resources