I have to create the following graph and i have to dynamically load data into it.
Basic Area http://domoticx.com/wp-content/uploads/highcharts-area-basic-standaard.png
Could anyone please help me understanding how can it be done.
Below is where i am able to reach.:
$.ajax({
url: 'EthicsData',
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8',
async: false,
processData: false,
cache: false,
delay: 150,
success: function (data) {
var EthicReg = (data[0].regdet);
var EthicComp = (data[0].compdet);
var EthicsCompletions = new Array();
var EthicsRegistration = new Array();
for (var i in EthicReg) {
var serie = new Array(EthicReg[i].Value, EthicReg[i].year);
EthicsRegistration.push(serie);
}
for (var y in EthicComp) {
var series2 = new Array(EthicComp[y].value,
EthicComp[y].year);
EthicsCompletions.push(series2);
}
DrawEthicsAndCompl(EthicsCompletions, EthicsRegistration)
},
error: function (xhr) {
alert('error');
}
});
};
function DrawEthicsAndCompl(EthicsCompletions, EthicsRegistration) {
debugger;
var chart = new Highcharts.Chart({
chart: {
//plotBackgroundColor: null,
//plotBorderWidth: 1, //null,
//plotShadow: false,
renderTo: 'container1',
type: 'area'
},
title: {
text: 'US and USSR nuclear stockpiles'
},
subtitle: {
text: 'something'
},
xAxis: {
allowDecimals: false,
labels: {
formatter: function () {
return 10; // clean, unformatted number for year
}
}
},
yAxis: {
title: {
text: 'Nuclear weapon states'
},
labels: {
formatter: function () {
return this.value;
}
}
},
tooltip: {
pointFormat: '{series.name} produced <b>{point.y:,.0f}</b><br/>warheads in {point.x}'
},
plotOptions: {
area: {
pointStart: 2010,
marker: {
enabled: false,
symbol: 'circle',
radius: 2,
states: {
hover: {
enabled: true
}
}
}
}
},
series: [{
name: 'Registration',
data: [EthicsRegistration[0]]
}, {
name: 'Completions',
data: [EthicsCompletions[0]]
}]
});
}
Here is the link which demo's same but static data:
(http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/area-basic/)
Just change the order in which you are pushing items in array , means
Instead
var serie = new Array(EthicReg[i].Value, EthicReg[i].year);
EthicsRegistration.push(serie);
Use
var serie = new Array(EthicReg[i].year, EthicReg[i].Value);
EthicsRegistration.push(serie);
Also , If you are getting year's value don't use pointStart: 2010 instead leave it on the data you are getting from the response above.
Thanks #Nishith for providing the right direction. I modified the code as below:
name: 'Registration',
data: [EthicsRegistration[0][1], EthicsRegistration[1][1], EthicsRegistration[2][1]]
}, {
name: 'Completions',
data: [EthicsCompletions[0][1],EthicsCompletions[1][1],EthicsCompletions[2][1]]
}]
});
Related
Hello there to all developers :-)
I want to ask a question about making Ajax Calls in the highchart.js library
I have some values which I am returning via Ajax based on the information I am giving to the back-end (its an MVC .NET project) and then I want to render a new chart in each div with the class gainChart (I am adding Ids for other purposes,so don't bother them :-) )
var iteratorJs = 0;
$(".gainChart").each(function (i) {
$(this).attr('id', "gainChart" + (i + 1));
var chart = new Highcharts.Chart({
chart: {
renderTo: this,
type: 'line',
margin: 0,
backgroundColor: 'rgba(255,255,255,0.3)'
},
colors: ['#2E5430'],
xAxis: {
lineWidth: 0,
minorGridLineWidth: 0,
lineColor: 'green',
//type: 'datetime',
labels: {
enabled: false
},
categories: [
$.ajax({
type: "POST",
url: "forex-copy-points-days",
data: { page: 0, perPage: 5, iterator: iteratorJs },
dataType: 'json',
async: false,
success: function (data) {
var daysArr = data.days;
JSON.stringify(daysArr);
categories = daysArr;
console.log(daysArr);
}
})
]
},
tooltip: {
formatter: function () {
var text = '';
text = this.y + '$';
return text;
}
},
credits: { enabled: false },
title: { text: null },
legend: {
enabled: false
},
plotOptions: {
series: {
stacking: 'normal',
pointWidth: 10
}
},
series: [{
name: 'Balance',
showInLegend: true,
legendMarkerColor: "green",
legendText: "Profit for account",
data: [
$.ajax({
type: "POST",
url: "forex-copy-points-balance",
data: { page: 0, perPage: 5, iterator: iteratorJs },
dataType: 'json',
async: false,
success: function (balances) {
var balArr = balances.balances;
JSON.stringify(balArr);
data = balArr;
console.log(balArr);
}
})
]
}],
exporting: {
enabled: false
},
responsive: {
rules: [{
condition: {
maxWidth: 600
},
chartOptions: {
legend: {
enabled: false
}
}
}]
}
});
iteratorJs++;
});
The returning data is as it is supposed to be (different strings), yet nothing is displayed - only the background of the chart. Can someone give me a clue how to solve this and what to change in order to solve my problem.
Thanks in advance!
The jQuery $.ajax method call doesn't return the data that results from this call, so you can't write myData = $.ajax(). You have to use the success callback to get the data, and then use it.
So for example, instead of writing this:
categories: [
$.ajax({
type: "POST",
url: "forex-copy-points-days",
data: { page: 0, perPage: 5, iterator: iteratorJs },
dataType: 'json',
async: false,
success: function (data) {
var daysArr = data.days;
JSON.stringify(daysArr);
categories = daysArr;
console.log(daysArr);
}
})
]
You should write something like this:
$.ajax({
type: "POST",
url: "forex-copy-points-days",
data: { page: 0, perPage: 5, iterator: iteratorJs },
dataType: 'json',
async: false,
success: function (data) {
// create graph from AJAX call results
var chart = new Highcharts.Chart({
xAxis: {
categories: JSON.stringify(data.days)
},
series: [{
data: JSON.stringify(balances.balances)
}]
});
}
});
I try to populate chart when user click on button .. and chart is display like this
now the problem i want total i.e. as in image in red circle i write TOTAL : 3 .. 3 is beacuse 2 for MV and 1 for DSB so total is 3
I try this
this is the code which i try
<script type="text/javascript">
var strArray = "[['sfdsdfLi', 9],['Kiwsdfi', 3],['Mixesdfd nuts', 1],['Oranges', 6],['Grapes (bunch)', 1]]";
$(function () {
$('#tabledata').on('click', 'tr', function () {
var row = $(this);
var Id = row.find('td')[0].firstChild.data;
var obj = {};
obj.ID = Id;
GetData(obj);
return false;
});
});
function GetData(obj) {
$.ajax({
type: "POST",
url: "WebForm1.aspx/GetVo",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
if (result !== null && result.length == 0) {
$("#cont").hide();
return;
}
strArray = result.d;
var myarray = eval(strArray);
$("#cont").show();
$('#cont').highcharts({
chart: {
borderColor: 'Grey',
borderWidth: 2,
type: 'pie',
options3d: {
enabled: true,
alpha: 45
}
},
title: {
text: 'Data1'
},
position: {
align: 'right',
verticalAlign: 'bottom',
x: 10,
y: -10
},
subtitle: {
text: '3D Chart'
},
plotOptions: {
pie: {
innerSize: 100,
depth: 45,
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.y}',
},
showInLegend: true
}
},
series: [{
name: 'Delivered amount',
data: myarray
}]
});
},
error: function (error) {
alert(error);
}
});
}
</script>
now how i get total ? any solutions
I have a method that get data from database and show it on chart. Its working fine. Now, i need to put some filters on it, and I'm facing dificulties to pass my parameters to the controller.
$("#quadro").click(function () {
Highcharts.setOptions({
lang: {
decimalPoint: ',',
thousandsSep: '.'
}
});
var data1 = $('#data1').val();
var data2 = $('#data2').val();
var empresa = $('#empresa option:selected').text();
$.ajax({
url: 'Painel/QuadroReceitas',
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8',
data: { 'data1': data1, 'data2': data2, 'empresa': empresa },
async: false,
processData: false,
cache: false,
delay: 15,
success: function (data) {
var Categories = new Array();
var FaturadoArray = new Array();
var RecebidoArray = new Array();
var AtrasadoArray = new Array();
for (var i in data) {
Categories.push(data[i].Mes);
FaturadoArray.push(data[i].Receitas);
RecebidoArray.push(data[i].Recebido);
AtrasadoArray.push(data[i].Inad_Atual);
}
var MesArray = JSON.parse(JSON.stringify(Categories));
quadroReceitas(MesArray, FaturadoArray, RecebidoArray, AtrasadoArray);
},
error: function (xhr) {
alert('error');
}
});
});
function quadroReceitas(MesArray, FaturadoArray, RecebidoArray, AtrasadoArray) {
var GlobalRotation = -90;
var GlobalAlign = 'right';
var X;
var Y;
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column',
realignLabels: true,
animation: false
},
title: {
text: 'Quadro de Receitas'
},
legend: {
align: 'left',
verticalAlign: 'top',
floating: true,
x: 0,
y: 0
},
xAxis: {
categories: MesArray,
crosshair: true,
},
yAxis: {
labels: { enabled: false },
title: { enabled: false },
},
credits: {
enabled: false
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:,.1f}</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
animation: true,
pointPadding: 0.05, // Defaults to 0.1
groupPadding: 0.05, // Defaults to 0.2
dataLabels: {
enabled: true,
rotation: GlobalRotation,
color: '#FFFFFF',
align: GlobalAlign,
verticalAlign: "top",
y: 10,
inside: false,
crop: false,
style: {
fontSize: '12px',
fontFamily: 'Verdana, sans-serif'
},
formatter: function () {
return Highcharts.numberFormat(this.y, 2);
}
}
},
},
series: [
{ name: 'Faturado', color: '#004a91', data: FaturadoArray },
{ name: 'Recebido', color: '#009147', data: RecebidoArray },
{ name: 'Atrasado', color: '#FF0000', data: AtrasadoArray }
]
});
}
On Controller i have the code as bellow:
[HttpGet]
public JsonResult QuadroReceitas(string data1, string data2, string empresa)
{
if(empresa == "empresa" || empresa == null)
{
empresa = "%";
}
//Chave oChave = new Chave();
DateTime agora = DateTime.Now;
var start = new DateTime(agora.Year, agora.Month, 1).AddMonths(-11);
var end = new DateTime(agora.Year, agora.Month, 1).AddMonths(1).AddDays(-1);
if (data1 == null)
data1 = start.ToShortDateString();
if (data2 == null)
data2 = end.ToShortDateString();
ContasReceberData recData = new ContasReceberData();
List<ContasReceber> receitas = new List<ContasReceber>();
receitas = recData.GetQuadroReceitas(data1, data2, empresa)
.Select(o => new ContasReceber
{
Mes = o.Mes,
Receitas = Math.Round(o.Receitas,2),
Recebido = Math.Round(o.Recebido, 2),
Inad_Atual = Math.Round(o.Inad_Atual, 2)
}).ToList();
return Json(receitas, JsonRequestBehavior.AllowGet);
}
As I told, it is working fine, but without the parameters:
data1, data2, empresa
I tried to change on AJAX to POST and Controller to HttpPost as i read in another topic but didnt work.
Because in your ajax method you set processData=false. set it to true or delete the line of processData and it's work!
var empresa = $('#empresa option:selected').text();
$.ajax({
url: 'Painel/QuadroReceitas',
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8',
data: { 'data1': data1, 'data2': data2, 'empresa': empresa },
async: false,
// processData: false,
cache: false,
delay: 15,
success: function (data) {
var Categories = new Array();
var FaturadoArray = new Array();
var RecebidoArray = new Array();
var AtrasadoArray = new Array();
for (var i in data) {
Categories.push(data[i].Mes);
FaturadoArray.push(data[i].Receitas);
RecebidoArray.push(data[i].Recebido);
AtrasadoArray.push(data[i].Inad_Atual);
}
var MesArray = JSON.parse(JSON.stringify(Categories));
quadroReceitas(MesArray, FaturadoArray, RecebidoArray, AtrasadoArray);
},
error: function (xhr) {
alert('error');
}
});
});
I am using ajax api calls for getting data from a SQL database as below:
function getJsonData(type, period1, period2, id) {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
type: "GET",
url: createURL(type, period1, period2, id),
dataType: "json",
contentType: "application/json; chartset=utf-8"
}
},
});
return dataSource;
}
Using the above datasource, I am creating a Kendo chart as below:
function stepsChart(container, title, period1, period2) {
var dSource = getJsonData("Summary", period1, period2, "<% = id %>");
$(container).kendoChart({
dataSource: dSource,
seriesColors: ["orangered"],
chartArea: {
background: ""
},
title: {
text:title
},
legend: {
visible: false
},
chartArea: {
background: ""
},
seriesDefaults: {
type: "column",
gap:5
},
series: [{
name: "steps",
field: "steps",
categoryField: "createddate",
aggregate: "sum"
}],
categoryAxis: {
type: "date",
baseUnit: getBaseUnit(period1, period2),
labels: {
rotation: -45,
dateFormats: {
days : getDateFormat(period1, period2),
weeks: getDateFormat(period1, period2),
years: getDateFormat(period1, period2)
},
step: getSteps(period1, period2)
},
majorGridLines: {
visible: false
}
},
valueAxis: {
majorGridLines: {
visible: true
},
labels: {
template: "#= kendo.format('{0}',value/1000)#K"
},
title: {
text: "Steps"
}
}
});
}
I also want to use the data from the above datasource for showing a summary of the information in a div below the chart. But if I add something like
var k = dSource.data;
there will not be any data in k. Is there a way to get the json data in the function which creates the chart?
DataSource.data is a function. I think your code should be:
var k = dSource.data();
That would also return an empty array if the data hasn't already been read, so you might need to do:
dSource.one("change", function () {
var k = dSource.data();
});
dSource.fetch();
because the .fetch() is async.
I have a problem using Highcharts.
I want to get an array from my php API and treat the results as my datapoints.
Here is the code :
$(function () {
$(document).ready(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
$('#graph_temperature').highcharts({
chart: {
zoomType: 'x',
type: 'area'
},
credits: {
enabled: false
},
title: {
text: 'Temperature'
},
legend: {
enabled: false
},
xAxis: {
type: 'datetime'
},
series: [{
name: 'Temperature',
color: '#ff851b',
marker: {
enabled: false
},
data: (function () {
var data_graph;
$.ajax({
url: "https://urlhidden.com/ajaxsql.php?f=get_all_temperature",
type: "GET",
async: false,
success: function (data) {
data_graph = [].concat(data);
$("#debug").html(data_graph);
}
});
return data_graph;
})()
}]
})
})
});
My array is like :
[[1394908920000,20.87], [1394908980000,20.87], [1394909040000,20.87], [1394909100000,20.87], [1394909160000,20.87], [1394909220000,20.87],...]
My problem is that Highchart doesnt draw my chart. Axis, title are OK but my area is missing.
In order to debug i used this line :
$("#debug").html(data_graph);
And the array is well formed as i can see in my "debug" div.
When i put manually the entire array :
data:[[1394908920000,20.87], [1394908980000,20.87], [1394909040000,20.87], [1394909100000,20.87], [1394909160000,20.87], [1394909220000,20.87],...],
it works well.
Anybody have an idea to help me ?
I haven't test my code but it should work.I hope you'll understand my idea.
$(function () {
$(document).ready(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
params = {
chart: {
zoomType: 'x',
type: 'area'
},
credits: {
enabled: false
},
title: {
text: 'Temperature'
},
legend: {
enabled: false
},
xAxis: {
type: 'datetime'
},
series: [{
name: 'Temperature',
color: '#ff851b',
marker: {
enabled: false
}
}]
};
$.ajax({
url: "https://urlhidden.com/ajaxsql.php?f=get_all_temperature",
type: "GET",
async: false,
context:document.body,
success: function (data) {
//data should be converted to json object using [..]
//remove data variable in this format you should get the data
data = [[1394908920000,20.87], [1394908980000,20.87], [1394909040000,20.87]];
params.series[0].data = data;
$('#graph_temperature').highcharts(params);
}
});
})
});
Updated