Javascript variable does not work inside an object. I see the data when I console.log(dataPondsRevenue) variable, but getting the error:
SyntaxError: missing ] after element list`!
when I use it inside the data:[] node:
$('.pondsRevenueBlock').on('click',function(){
var block_id = $(this).attr('data-id');
var url='{{ route('WhiteFish.client.pondsRevenueBlockWise') }}';
$.ajax({
url:url+'?block_id='+block_id,
}).done(function(pondsRevenueData){
var dataPondsRevenue = '';
$.each(pondsRevenueData, function(index, element) {
dataPondsRevenue+= '{value:'+element.pondTotalInvest+',name:'+element.name+'},';
});
console.log(dataPondsRevenue);
var eChart_2 = echarts.init(document.getElementById('pondsRevenue'));
var option1 = {
tooltip : {
backgroundColor: 'rgba(33,33,33,1)',
borderRadius:0,
padding:10,
axisPointer: {
type: 'cross',
label: {
backgroundColor: 'rgba(33,33,33,1)'
}
},
textStyle: {
color: '#fff',
fontStyle: 'normal',
fontWeight: 'normal',
fontFamily: "'Open Sans', sans-serif",
fontSize: 12
}
},
// color: ['#0FC5BB', '#92F2EF', '#D0F6F5'],
color: ['#0FC5BB', '#0FC5BB', '#5AC4CC'],
series : [
{
name: 'task',
type: 'pie',
radius : '55%',
center: ['50%', '50%'],
roseType : 'radius',
tooltip : {
trigger: 'item',
formatter: "{a} <br/>{b} : {c} ({d}%)",
backgroundColor: 'rgba(33,33,33,1)',
borderRadius:0,
padding:10,
textStyle: {
color: '#fff',
fontStyle: 'normal',
fontWeight: 'normal',
fontFamily: "'Open Sans', sans-serif",
fontSize: 12
}
},
data:[
console.log(dataPondsRevenue);
],
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
eChart_2.setOption(option1);
eChart_2.resize();
}).fail(function (data) {
console.log('error');
});
});
How can I solve it?
Use an array (and optionally JSON.stringify it; in case of $.ajax, have a look at contentType at $.ajax docs), it is much less error-prone - in your case, there's always a trailing comma at the end, which is not a valid JSON:
console.log("Valid:")
console.log(JSON.parse('{ "whatever": 1 }'))
console.log("Invalid:")
console.log(JSON.parse('{ "whatever": 1, }'))
$('.pondsRevenueBlock').on('click',function(){
var block_id = $(this).attr('data-id');
var url='{{ route('WhiteFish.client.pondsRevenueBlockWise') }}';
$.ajax({
url:url+'?block_id='+block_id,
contentType: 'application/json'
}).done(function(pondsRevenueData){
var dataPondsRevenue = [];
$.each(pondsRevenueData, function(index, element) {
dataPondsRevenue.push({
value: element.pondTotalInvest,
name: element.name
})
});
console.log(dataPondsRevenue);
var eChart_2 = echarts.init(document.getElementById('pondsRevenue'));
var option1 = {
tooltip : {
backgroundColor: 'rgba(33,33,33,1)',
borderRadius:0,
padding:10,
axisPointer: {
type: 'cross',
label: {
backgroundColor: 'rgba(33,33,33,1)'
}
},
textStyle: {
color: '#fff',
fontStyle: 'normal',
fontWeight: 'normal',
fontFamily: "'Open Sans', sans-serif",
fontSize: 12
}
},
// color: ['#0FC5BB', '#92F2EF', '#D0F6F5'],
color: ['#0FC5BB', '#0FC5BB', '#5AC4CC'],
series : [
{
name: 'task',
type: 'pie',
radius : '55%',
center: ['50%', '50%'],
roseType : 'radius',
tooltip : {
trigger: 'item',
formatter: "{a} <br/>{b} : {c} ({d}%)",
backgroundColor: 'rgba(33,33,33,1)',
borderRadius:0,
padding:10,
textStyle: {
color: '#fff',
fontStyle: 'normal',
fontWeight: 'normal',
fontFamily: "'Open Sans', sans-serif",
fontSize: 12
}
},
data: JSON.stringify(dataPondsRevenue),
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
eChart_2.setOption(option1);
eChart_2.resize();
}).fail(function (data) {
console.log('error');
});
});
Also, the console.log(), returns undefined - you can just pass the variable instead.
There seems to be quite a confusion as to how to create the needed data object. With the code
$.each(pondsRevenueData, function(index, element) {
dataPondsRevenue+= '{value:'+element.pondTotalInvest+',name:'+element.name+'},';
});
You are creating a JSON string. This could be parsed into an object using JSON.parse() but that seems unnecessary over complication as you could create the required array of objects to start with:
var dataPondsRevenue = [];
$.each(pondsRevenueData, function(index, element) {
dataPondsRevenue.push({value: element.pondTotalInvest, name: element.name});
});
Then, just assign dataPondsRevenue to data:
...
},
data: dataPondsRevenue,
itemStyle:
...
This is because console.log(dataPondsRevenue) is a function that returns undefined, so
data: [ console.log(dataPondsRevenue) ]
means
data: [ undefined ]
You should do
data: [ dataPondsRevenue ]
to get the actual data into the array.
You are creating a JSON string. This could be parsed into an object using JSON.parse() but that seems unnecessary over complication as you could create the required array of objects to start with:
var dataPondsRevenue = [];
$.each(pondsRevenueData, function(index, element) {
dataPondsRevenue.push({value: element.pondTotalInvest, name: element.name});
});
Related
I need a column chart data with JSON, in order to automate this chart, but i dont no how do this.
So this is my JS Code:
function drawChart() {
const container = document.querySelector('#chart');
let chart = new google.visualization.ColumnChart(container);
//Informações data.json
let dataRequest = new Request("./datas/data.json");
fetch(dataRequest)
.then(function(resp) {
return resp.json();
})
.then(function(data) {
console.log(data);
});
// Informações gráficos
let data = new google.visualization.arrayToDataTable([
["Volume", "Valor"],
["DA", 67],
["CIF", 23],
["Expurgo", 45]
]);
const options = {
titlePosition: 'none',
colors: ['#ed4a0e', '#15466e'],
backgroundColor: 'transparent',
animation: {
startup: true,
duration: 1000,
easing: 'out',
},
hAxis: { textStyle: { color: 'white' }, titleTextStyle: { color: 'white', fontSize: 15 } },
vAxis: { textStyle: { color: 'white' }, titleTextStyle: { color: 'white', fontSize: 15 } },
chartArea: { width: 250, height: 200 },
legend: {
textStyle: { color: '#ffffff', fontSize: 13 }
}
};
chart.draw(data, options)
};
My json:
[
["Volume", "Valor"],
["DA", 67],
["CIF", 23],
["Expurgo", 45]
]
I never do this before, and need a little help,if someone help whit this
(Sorry for my bad english)
Add "false" as last parameter
var data = google.visualization.arrayToDataTable([
["Volume", "Valor"],
["DA", 67],
["CIF", 23],
["Expurgo", 45]
],
false); // 'false' means that the first row contains labels, not data.
html
js
var myChart = echarts.init(document.getElementById("main"));
window.onresize = myChart.resize;
var statistics = {
title: {
text: "面积",
textStyle: {
fontWeight: "normal",
color: "#fff",
fontSize: 14
},
left: "center"
},
tooltip: {
// 鼠标移动柱状图是提示文字
show: true
},
legend: {
// data: ['面积'],
textStyle: {
fontSize: 12
}
},
xAxis: {
data: ["灌木", "森林", "森林", "树木", "小树", "大树", "红树"],
axisLabel: {
show: true,
textStyle: {
color: "#fff"
}
},
axisLine: {
lineStyle: {
color: "#094060"
}
}
},
yAxis: {
axisLine: {
lineStyle: {
color: "#094060"
}
},
axisLabel: {
show: true,
textStyle: {
color: "#fff"
}
},
splitLine: {
lineStyle: {
color: ["#07405c"]
}
}
},
itemStyle: {
color: "#06ae7c",
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: "rgba(0, 0, 0, 0.5)"
}
},
series: [
{
type: "bar",
barWidth: 48,
data: [38, 23, 35, 12, 26, 8, 36]
}
]
};
myChart.setOption(statistics);
The echarts container in the tab switch width is set to 100%, but no matter how to set the width, are only 100px, the Internet that is because the tab bar tried to hide cause, many of the above methods, are not normal display, followed by window.onresize = myChart.resize in the code; only when changing the size of the browser window to display properly, but if you do not change the size of the window or after 100px, before we have encountered this kind of situation is how to solve?
put the class "echart" in each div chart, and execute that in your js.
$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
$(".echart").each(function() {
var id = $(this).attr('echarts_instance');
window.echarts.getInstanceById(id).resize();
});
});
I have discovered one workaround for this issue. Try to call the resize event of window object when you switch tabs. To achieve it with jQuery is straightforward:
$(window).trigger('resize');
var myChart=$("#myChart");
myChart.style.width=window.innerWidth+'px';
chartObj=echarts.init(myChart);
chartObj.setOption(option);
I am working with pdfMake, that converts the static text into pdf.
My text in HTML is coming from a service in AngularJS and is dynamic. The text can have both English as well as non-English characters like Korean, Japanese, Chinese, etc.
Currently, I have only English font, so it prints blank for the non-English characters.
How can one fix this issue?
The JS code:
self.downloadAsPdf = function (dateTimeId) {
var datetime = document.getElementById(dateTimeId).innerHTML;
pdfMake.fonts = {
proximaNova: {
normal: 'proximanova-regular.ttf',
bold: 'Roboto-Medium.ttf',
italics: 'proximanova-light.ttf',
bolditalics: 'proximanova-semibold.ttf'
}
};
var docDefinition = {
{ text: 'Heading', style: 'header' },
{ text: 'Subheading', style: 'myscript' },
{ text: datetime, style: 'datetime' },
{ text: model.storyScriptData.personalMoment, style: 'body' },
{ text: model.storyScriptData.createAConnection, style: 'body' },
{ text: model.storyScriptData.theResoultion, style: 'body' }
],
defaultStyle: {
font: 'proximaNova'
},
styles: {
header: {
fontSize: 24,
alignment: 'center',
color: "#ffffff",
margin: [0, 60, 0, 0]
},
myscript: {
fontSize: 18,
alignment: 'left',
color: "#a7a7a7",
margin: [0, 100, 0, 0]
},
datetime: {
fontSize: 11,
alignment: 'left',
color: "#a7a7a7",
margin: [0, 2, 0, 36]
},
body: {
fontSize: 13,
alignment: 'left',
color: "#727272",
lineHeight: 1.5,
bolditalics: true
}
}
}
pdfMake.createPdf(docDefinition).download('optionalName.pdf');
}
where model.storyScriptData.personalMoment, model.storyScriptData.createAConnection and model.storyScriptData.theResoultion are the model's in AngularJS
Suposing that you know which language is being used at each time, and that you can receive it from model on some atribute as model.storyScriptData.currentLanguage.
You should have a object similar to:
var fonts = {
english: 'english_font_name',
japanese: 'japanese_font_name',
chinese: 'chinese_font_name',
korean: 'korean_font_name'
}
Then you can choose the correct font for each language:
defaultStyle: {
font: fonts[model.storyScriptData.currentLanguage]
}
You can add custom fonts to your pdfMake instance, as on their documentation here.
Also, explained a bit differently in this response.
I'm using highCharts, and creating a highChart in fancybox. I want animation off in highCharts. but when I set 'animation: false' the bars in the charts disappears
I don't know what's the problem I've tried many things, if I create highChart without fancybox it creates ok, but fancybox is the requirement. below is my code createHighChart() function create HighChart from the settings that user would set on the page.
$.fancybox.open({
'href' : '#container',
'titleShow' : false,
'transitionIn' : 'elastic',
'transitionOut' : 'elastic',
prevEffect : 'none',
nextEffect : 'none',
afterShow: function(){
for(var i=0; i<10000; i++);
createHighChart();
$("#container").show();
}
});
and createHighChart function:
function createHighChart() {
var xData = getXdata();
var yAxisData = getYAxisData();
var t = getInt("threshold_id");
var type = getType();
var backColors = getBackgroundColor();
var isAreaOrLineChart = false;
var customColors = false;
var customPlotOptions = Highcharts.getOptions().plotOptions;
/*uncomment following two lines to provide your custom
* colors (an array of colors) for the bars in bar chart*/
/*customColors = true;
customPlotOptions.column.colors = customPlotOptions.bar.colors =
['#FF0000', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572'];*/
/***************************change font style****************************/
/*Highcharts.setOptions({
chart: {
style: {
fontSize: '25px',
fontWeight: 'bold',
fontFamily: 'serif',
}
}
});*/
if(type == "pie") {
createPieChart();
return;
}
if(type == "line" || type == "area") {
isAreaOrLineChart = true;
}
/******************Bar chart specific settings************************/
var barColor = getStr("barcolor_id");
var isMultiColor = false;
if(barColor == "multicolor") {
barColor = null;
isMultiColor = true;
}
else if(barColor == "") {
barColor = null;
}
if(isStacking() == "normal"){
barColor = isMultiColor = null;
}
var isGrouping = true;
if(getStr("barlayout_id") == "overlap") {
isGrouping = false;
barColor = isMultiColor = null;
}
/******************Line chart specific settings************************/
var thickLine = 2;
if(isCheckBoxEnabled("thickline_id")){
thickLine = 5;
}
/*if(isCheckBoxEnabled("show3d_id")) {
loadjsfile();
}
else {
$("#scripto").remove();
//removejsfile();
}
*/
/*******************Creates the bar chart************************/
var chart = new Highcharts.Chart({
chart : {
//backgroundColor: getStr("chrtbkgndcolor_id"),
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 1, y2: 1 },
stops: [
[0, backColors[0]],
[1, backColors[1]]
]
},
renderTo : 'container',
type : type,
margin: 75,
//animation: false,
options3d: {
enabled: isCheckBoxEnabled("show3d_id") && !isAreaOrLineChart,
alpha: 10,
beta: 10,
depth: 50,
viewDistance: 25
},
borderColor: '#A9A9A9',
borderRadius: isRoundCorner(),
borderWidth: isBorder(),
width: getInt("width_id"),
height: getInt("height_id")
},
title : {
text : getStr("title_id"),
style: {
fontWeight: getFontWeight("fonttypetitle_id"),
fontStyle: getFontStyle("fonttypetitle_id")
}
},
subtitle: {
text: getStr("subtitle_id"),
style: {
fontWeight: getFontWeight("fonttypetitle_id"),
fontStyle: getFontStyle("fonttypetitle_id")
}
},
tooltip: {
enabled: isCheckBoxEnabled("tooltip_id")
},
credits: {
text: getStr("source_id"),
href: '#'
},
legend: {
enabled: isCheckBoxEnabled("legend_id"),
},
xAxis : {
title:{
text: getStr("xtitle_id"),
style: {
fontWeight: getFontWeight("fonttypetitle_id"),
fontStyle: getFontStyle("fonttypetitle_id")
}
},
categories : xData,
labels: {
rotation: getRotation(),
style: {
fontWeight: getFontWeight("fonttypelabel_id"),
fontStyle: getFontStyle("fonttypelabel_id")
}
},
/*below two lines are for x-axis line, it is not working
* due to inclusion of the 3D charts library
* (namely this line:
* <script src="http://code.highcharts.com/highcharts-3d.js"></script>)
* in the include/ChartGoLiteJSFiles.jsp */
lineWidth: 1,
lineColor: '#FF0000',
gridLineWidth: false
},
yAxis :
{
//lineWidth: 20,
min: getMinMaxY("min_yaxis_id"),
max: getMinMaxY("max_yaxis_id"),
plotLines: [{
color: '#FF0000',
width: 2,
value: t,
dashStyle: 'shortdash',
id: 'plotline-1'
}],
title : {
text : getStr("ytitle_id"),
style: {
fontWeight: getFontWeight("fonttypetitle_id"),
fontStyle: getFontStyle("fonttypetitle_id")
}
},
labels: {
style: {
fontWeight: getFontWeight("fonttypelabel_id"),
fontStyle: getFontStyle("fonttypelabel_id")
}
},
/*below two lines are for x-axis line, it is not working
* due to inclusion of the 3D charts library
* (namely this line:
* <script src="http://code.highcharts.com/highcharts-3d.js"></script>)
* in the include/ChartGoLiteJSFiles.jsp */
lineWidth: 1,
lineColor: '#FF0000',
gridLineColor: '#197F07',
gridLineWidth: isCheckBoxEnabled("gridlines_id")
},
plotOptions: {
series: {
animation: false,//this is not working right
shadow: isShadow(),
color: barColor,
//colorByPoint: isMultiColor || customColors,
stacking: isStacking(),
marker: {
enabled: isCheckBoxEnabled("shape_id")
},
lineWidth: thickLine
},
column: {
//animation: false,
colorByPoint: isMultiColor || customColors,
depth: 25,
grouping: isGrouping
},
bar: {
colorByPoint: isMultiColor || customColors,
},
},
series : yAxisData
});
chart.container.onclick = isCheckBoxEnabled("mouse_interaction_id");
if(t == 0)
chart.yAxis[0].removePlotLine('plotline-1');
}
After setting up my first chart I'm looking to add check-boxs to toggle which series are selected.
Flot provides an example here : http://www.flotcharts.org/flot/examples/series-toggle/
Now when i tried to replicate this I'm getting error: 'datasets' is undefined could anyone explain why??
Also bonus points if anyone can tell my why the legend still display's inside the graph?
Chart Looks like :
View Code :
<div class="legend-container"></div>
<div class="graph-container">
<div id="placeholder" class="graph-placeholder"></div>
</div>
<p id="choices"></p>
Chart Code:
$(document).ready(function fetchData() {
function onDataReceived(series)
{
console.log('recieved data now parsing the data');
var currentdata = $.parseJSON(series);
//Testing
console.log(currentdata);
console.log("series sub-arrays");
console.log(currentdata[0]);
console.log(currentdata[1]);
console.log(currentdata[2]);
var datasets = [
{
label: "Current_Out",
data: currentdata[0],
yaxis: 2,
color: '#00C932',
points: { fillColor: "#00C932", show: true },
lines: { show: true }
}, {
label: "Temperature",
data: currentdata[1],
yaxis: 1,
color: "#0062FF",
points: { fillColor: "#0062FF", show: true },
lines: {show:true }
}]
var options = {
legend: {
show: true,
placement: 'outsideGrid',
container: $("#legend-container")
},
lines: {
show: true,
fill: false,
},
axisLabels: {
show: true
},
xaxes: [{
mode: "time",
timeformat: "%H:%M:%S",
axisLabel:'Date',
axisLabelUseCanvas: false,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial, Helvetica, Tahoma, sans-serif',
axisLabelPadding: 5
}],
yaxes: [{
position: "left",
axisLabel:'Celcius',
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial, Helvetica, Tahoma, sans-serif',
axisLabelPadding: 5
}, {
position: "right",
axisLabel: 'mA'
}],
grid: {
hoverable: true,
clickable: true,
borderWidth: 1
},
legend: {
labelBoxBorderColor: "none",
position: "right"
},
points: {
show: true,
fillColor: "#000000"
}
};
$.plot($("#placeholder"), datasets, options);
}
$.ajax({
url: '/Ajax/GetGraphData',
type: "GET",
dataType: "json",
success: onDataReceived,
failure: function() {
console.log('Fail!');
}
});
Jquery for Checkbox's
// insert checkboxes
var choiceContainer = $("#choices");
$.each(datasets, function (key, val) {
choiceContainer.append('<br/><input type="checkbox" name="' + key +
'" checked="checked" id="id' + key + '">' +
'<label for="id' + key + '">'
+ val.label + '</label>');
});
choiceContainer.find("input").click(plotAccordingToChoices);
function plotAccordingToChoices() {
var data = [];
choiceContainer.find("input:checked").each(function () {
var key = $(this).attr("name");
if (key && datasets[key])
data.push(datasets[key]);
});
if (data.length > 0)
$.plot($("#placeholder"), data, {
yaxis: { min: 0 },
xaxis: { tickDecimals: 0 }
});
}
plotAccordingToChoices();
Scoping issue. var datasets is local to the onDataReceived function. It is not accessible outside that function. Initing it to null in the $(document).ready( handler should make it accessible to everything in that scope.
As for your second question, you need to show us the CSS attached to those divs. I'm guessing your graph-container is absoluting positioned. Also, in your options, you have two different configurations for legend. Delete the second one.