Related
I am facing an issue with displaying apexcharts on dashboard. I have 5 charts in dashboard and the charts behavior is pretty weird. All charts appears after reload the page 3 to 4 times or when clicked on inspect element. Otherwise shows 2 or 3 charts.How to fix this issue.
Let's have a look...
This is the Js file where Iam fetching all the data through ajax.
when I do console log I can see values in data key.
var revenueData = [];
var fetchEarningData = function() {
$.ajax({
url: "dashboard/earning",
type: "Get",
dataType: "json",
cache: false,
success: function (data) {
jQuery.map(data, function (n) {
revenueData.push(n)
});
},
complete: function (data) {
},
error: function (data) {
}
});
}
var customerData = [];
var fetchCustomerData = function (){
$.ajax({
url: "dashboard/customer",
type: "Get",
dataType: "json",
cache: false,
success: function (data) {
customerData.push(data)
},
complete: function (data) {
},
error: function (data) {
}
});
}
var fetchMemberData = function (){
$.ajax({
url: "dashboard/member",
type: "Get",
dataType: "json",
cache: false,
success: function (data) {
customerData.push(data)
},
complete: function (data) {
},
error: function (data) {
}
});
}
var orderData = [];
var fetchOrderData = function (){
$.ajax({
url: "dashboard/order",
type: "Get",
dataType: "json",
cache: false,
success: function (data) {
jQuery.map(data, function(n) {
orderData.push(n)
});
},
complete: function (data) {
handleRenderChart()
},
error: function (data) {
}
});
};
var stockInAmount = [];
var fetchStockInAmountData = function (){
$.ajax({
url: "dashboard/stockIn-amount",
type: "Get",
dataType: "json",
cache: false,
success: function (data) {
// console.log('new',data)
// Prepare series & xaxis category data for stacked100 region chart
jQuery.map(data, function (n) {
stockInAmount.push(n)
});
},
complete: function (data) {
},
error: function (data) {
}
});
}
var debitData = [];
var fetchDebitData = function (){
$.ajax({
url: "dashboard/debit-amount",
type: "Get",
dataType: "json",
cache: false,
success: function (data) {
jQuery.map(data, function(n) {
debitData.push(n)
});
},
complete: function (data) {
},
error: function (data) {
}
});
}
var creditData = [];
var fetchCreditData = function (){
$.ajax({
url: "dashboard/credit-amount",
type: "Get",
dataType: "json",
cache: false,
data: {
},
success: function (data) {
jQuery.map(data, function(n) {
creditData.push(n)
});
},
complete: function (data) {
},
error: function (data) {
}
});
}
var handleRenderChart = function() {
// global apexchart settings
Apex = {
title: {
style: {
fontSize: '14px',
fontWeight: 'bold',
fontFamily: app.font.family,
color: app.color.white
},
},
legend: {
fontFamily: app.font.family,
labels: {
colors: '#fff'
}
},
tooltip: {
style: {
fontSize: '12px',
fontFamily: app.font.family
}
},
grid: {
borderColor: 'rgba('+ app.color.whiteRgb + ', .25)',
},
dataLabels: {
style: {
fontSize: '12px',
fontFamily: app.font.family,
fontWeight: 'bold',
colors: undefined
}
},
xaxis: {
axisBorder: {
show: true,
color: 'rgba('+ app.color.whiteRgb + ', .25)',
height: 1,
width: '100%',
offsetX: 0,
offsetY: -1
},
axisTicks: {
show: true,
borderType: 'solid',
color: 'rgba('+ app.color.whiteRgb + ', .25)',
height: 6,
offsetX: 0,
offsetY: 0
},
labels: {
style: {
colors: '#fff',
fontSize: '12px',
fontFamily: app.font.family,
fontWeight: 400,
cssClass: 'apexcharts-xaxis-label',
}
}
},
yaxis: {
labels: {
style: {
colors: '#fff',
fontSize: '12px',
fontFamily: app.font.family,
fontWeight: 400,
cssClass: 'apexcharts-xaxis-label',
}
}
}
};
// small stat chart
var x = 0;
var chart = [];
var elmList = [].slice.call(document.querySelectorAll('[data-render="apexchart"]'));
elmList.map(function(elm) {
var chartType = elm.getAttribute('data-type');
var chartHeight = elm.getAttribute('data-height');
var chartTitle = elm.getAttribute('data-title');
var chartColors = [];
var chartPlotOptions = {};
var chartData = [];
var chartStroke = {
show: false
};
if (chartType === 'bar') {
chartColors = [app.color.theme];
chartPlotOptions = {
bar: {
horizontal: false,
columnWidth: '65%',
endingShape: 'rounded'
}
};
chartData = [{
name: chartTitle,
data: revenueData
}];
} else if (chartType === 'pie') {
chartColors = ['rgba('+ app.color.themeRgb + ', 1)', 'rgba('+ app.color.themeRgb + ', .75)', 'rgba('+ app.color.themeRgb + ', .5)'];
chartData = customerData
} else if (chartType === 'donut') {
chartColors = ['rgba('+ app.color.themeRgb + ', .15)', 'rgba('+ app.color.themeRgb + ', .35)', 'rgba('+ app.color.themeRgb + ', .55)', 'rgba('+ app.color.themeRgb + ', .75)', 'rgba('+ app.color.themeRgb + ', .95)'];
chartData = stockInAmount;
chartStroke = {
show: false,
curve: 'smooth',
lineCap: 'butt',
colors: 'rgba(' + app.color.blackRgb + ', .25)',
width: 2,
dashArray: 0,
};
chartPlotOptions = {
pie: {
donut: {
background: 'transparent',
}
}
};
} else if (chartType === 'line') {
chartColors = [app.color.theme];
chartData = [{
name: chartTitle,
data: orderData
}];
chartStroke = {
curve: 'straight',
width: 2
};
}
var chartOptions = {
chart: {
height: chartHeight,
type: chartType,
toolbar: {
show: false
},
sparkline: {
enabled: true
},
},
dataLabels: {
enabled: false
},
colors: chartColors,
stroke: chartStroke,
plotOptions: chartPlotOptions,
series: chartData,
grid: {
show: false
},
tooltip: {
theme: 'dark',
x: {
show: false
},
y: {
title: {
formatter: function (seriesName) {
return ''
}
},
formatter: (value) => { return ''+ value },
}
},
xaxis: {
labels: {
show: true
}
},
yaxis: {
labels: {
show: true
}
}
};
chart[x] = new ApexCharts(elm, chartOptions);
chart[x].render();
x++;
});
var serverChartOptions = {
chart: {
height: '100%',
type: 'bar',
toolbar: {
show: false
}
},
plotOptions: {
bar: {
horizontal: false,
columnWidth: '55%',
endingShape: 'rounded'
},
},
dataLabels: {
enabled: false
},
grid: {
show: true,
borderColor: false,
},
stroke: {
show: false
},
colors: ['rgba('+ app.color.whiteRgb + ', .25)', app.color.theme],
series: [
{
name: 'DEBIT',
data: debitData
},
{
name: 'CREDIT',
data: creditData
}],
xaxis: {
// categories: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', 30],
labels: {
show: true
}
},
fill: {
opacity: .65
},
tooltip: {
y: {
formatter: function (val) {
return "BDT " + val
}
}
}
};
var apexServerChart = new ApexCharts(
document.querySelector('#chart-server'),
serverChartOptions
);
apexServerChart.render();
};
fetchEarningData()
fetchMemberData()
fetchCreditData()
fetchDebitData()
fetchOrderData()
/* Controller
------------------------------------------------ */
$(document).ready(function() {
// window.location = window.location.href;
// setInterval(function(){
// window.location.reload();
//
// }, 3000);
// setInterval(10000);
// handleRenderChart()
document.addEventListener('theme-reload', function() {
$('[data-render="apexchart"], #chart-server').empty();
handleRenderChart()
});
let serial = 1;
fetch(`dashboard/top-products`)
.then(res => res.json())
.then(res => {
// console.log(res)
$('#topProducts').html(res.map((topProducts) => ` <tbody>
<tr>
<td>
<div class="d-flex">
<div class="position-relative mb-2">
<div class="position-absolute top-0 start-0">
<span class="badge bg-theme text-theme-900 rounded-0 d-flex align-items-center justify-content-center w-20px h-20px">${serial++}</span>
</div>
</div>
<div class="flex-1 ps-3">
<div class="mb-1"><small class="fs-9px fw-500 lh-1 d-inline-block rounded-0 badge bg-white bg-opacity-25 text-white text-opacity-75 pt-5px">${topProducts.barcode_number}</small></div>
<div class="fw-500 text-white">${topProducts.title}</div>
BDT ${topProducts.price}
</div>
</div>
</td>
<td>
<table class="mb-2 mt-2">
<tr>
<td class="pe-3">TOTAL SOLD:</td>
<td class="text-white text-opacity-75 fw-500">${topProducts.total}</td>
</tr>
<tr>
<td class="pe-3">REVENUE:</td>
<td class="text-white text-opacity-75 fw-500">${topProducts.total * topProducts.price} BDT</td>
</tr>
</table>
</td>
<td>
<i class="bi bi-search"></i>
</td>
</tr>
</tbody>` ))
})
});
it seems worked for me. ie; dynamically generate the chart div on on each function call to draw chart data
<div class="card" style="padding:0" id="charts">
<div class="card-body" style="padding:0" id="tagchart">
<div id="chart"></div>
</div>
var c = document.getElementById("tagchart");
var d = document.getElementById("chart");
c.removeChild(d);
var newdiv = document.createElement("div");
newdiv.setAttribute("id", "chart");
c.appendChild(newdiv);
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 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 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]]
}]
});
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