How to display data inside the script? - javascript

This is my current code, the problem is I dont know how to return the value, i dont know why the author from my function are undefined, what i want is to get the data from my query and pass it to the const reportChart, please help, thanks
this is my full code? did i miss something?
<script>
async function myFunction() {
var author = ("SELECT name FROM People", 10, (value)=>{
console.log(value)//please see the data below
return value;
})
return author; //undefined
}
myFunction().then(function(value){reportChart(value);})
const reportChart = (value) => {
console.log("inside chart: ",value) //The value of value is undefined
$("#chart").kendoChart({
title: {
text: "School Library"
},
legend: {
visible: false
},
seriesDefaults: {
type: "bar"
},
series: [{
name: "Total Visits",
data: [1, 2, 3]
}, {
name: "Total Visits",
data: [1, 2, 3]
}],
valueAxis: {
max: 10,
line: {
visible: false
},
minorGridLines: {
visible: true
},
labels: {
rotation: "auto"
}
},
categoryAxis: {
categories: [value],//undefined
majorGridLines: {
visible: false
}
},
tooltip: {
visible: true,
template: "#= series.name #: #= value #"
}
});
}
$(document).ready(reportChart);
$(document).bind("kendo:skinChange", reportChart);
</script>
the result of console.log(value)
0: ['Mark'] 1: ['Joseph'] 2: ['Luna'] 3: ['Yuno']
Update
I remove some code and replace this
<script>
let myPromise = new Promise(function(myResolve, myReject){
var author = ("SELECT name FROM People", 10, (value) => {
return myResolve(value)
});
})
myPromise.then(
function(value) {reportChart(value);},
function(error) {reportChart(error);}
);
function reportChart (value, index) {
console.log(index, value.length)
var i = 0
var author= []
for(i=0; i<=value.length; i++)
{
author[i] = value[i]
}
$("#chart").kendoChart({
title: {
text: "Library"
},
legend: {
visible: false
},
seriesDefaults: {
type: "bar"
},
series: [{
name: "Total Visits",
data: [1,2,3,4]
}, {
name: "Total Visits",
data: [4,5,6,7]
}],
valueAxis: {
max: 10,
line: {
visible: false
},
minorGridLines: {
visible: true
},
labels: {
rotation: "auto"
}
},
categoryAxis: {
categories: [author],
majorGridLines: {
visible: false
}
},
tooltip: {
visible: true,
template: "#= series.name #: #= value #"
}
});
}
$(document).ready(reportChart);
$(document).bind("kendo:skinChange", reportChart);
</script>
**
this is now the result
What I want is, please help

Here: listsOfPeople = value, I guess what you would like to to is listsOfPeople.push(value); instead?
Your code should be like var author = doQuery("SELECT name FROM People"....
Possible issues:
doQuery() changes listsOfPeople unexpectedly.
Just some typo mistake on your variable name.
Or you mixed the use of listsOfPeople and listsOfAuthor.

Related

Convert json data to object

Good Day Developers!
I'm facing issue in JSON object received from MVC controller to AJAX success request.
The response which received is below.
[
{"name":"ERP Developer","value":2},
{"name":"Software Engineer","value":2},
{"name":"Dot Net Developer","value":2},
{"name":"Apex Developer","value":0},
{"name":"test","value":1}
]
But i want to make it like below.
{
"name": [
"ERP Developer",
"Software Engineer"
],
"Value": [
5,
10
]
}
Problem: Because i'm creating Bar chart using ECHARTS library but i want series name instead of number please see below image for reference.
function loadBarChart(data,title = "JobData",subtext = "Artistic Milliners") {
//var BarDBData = data;
var BarDBData = data;
//var BarDBData = JSON.parse('{"name":["ERP Developer","TEST"],"test":[5,10]}');
console.log(BarDBData);
var chartDom = document.getElementById('BarChart');
var myChart = echarts.init(chartDom);
var option;
option = {
title: {
text: title,
subtext: subtext
},
tooltip: {
trigger: 'axis'
},
toolbox: {
show: true,
feature: {
dataView: { show: true, readOnly: false },
magicType: { show: true, type: ['line', 'bar'] },
saveAsImage: { show: true }
}
},
calculable: true,
xAxis: [
{
type: 'category',
// prettier-ignore
//data: ["ERP Developer", "Software Engineer"],
data: BarDBData,
axisLabel: { interval: 0, rotate: 30 }
}
],
yAxis: [
{
type: 'value'
}
],
dataZoom: [
{
show: true,
start: 04,
end: 100
},
{
type: 'inside',
start: 44,
end: 100
},
{
show: true,
yAxisIndex: 0,
filterMode: 'empty',
width: 30,
height: '80%',
showDataShadow: false,
left: '93%'
}
],
series: [
{
name: "test",
type: 'bar',
data: BarDBData,
//data: [2.0, 4.9, 4, 9, 4],
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#83bff6' },
{ offset: 0.5, color: '#188df0' },
{ offset: 1, color: '#188df0' }
])
},
markPoint: {
data: [
{ type: 'max', name: 'Max' },
{ type: 'min', name: 'Min' }
]
}
}
]
};
option && myChart.setOption(option);
}
you can just map through array and extract values into another array
const result = {}
const arr = [{"name":"ERP Developer","value":2},{"name":"Software Engineer","value":2},{"name":"Dot Net Developer","value":2},{"name":"Apex Developer","value":0},{"name":"test","value":1}]
arr.forEach(row => {
for (let i in row) {
if (result[i]) {
result[i].push(row[i])
} else {
result[i] = [row[i]]
}
}
})
console.log(result)
Just reduce() it into the desired shape:
const response = [
{"name":"ERP Developer","value":2},
{"name":"Software Engineer","value":2},
{"name":"Dot Net Developer","value":2},
{"name":"Apex Developer","value":0},
{"name":"test","value":1}
];
const mapped = response.reduce(
(acc,x) => {
acc.name.push( x.name );
acc.Value.push( x.value );
return acc;
},
{ name: [], Value: [] }
);

Highcharts how to add treemap upon click event on line chart?

Anyone know how to add treemap upon click event on line chart point? Here's my JSFiddle link:
https://jsfiddle.net/ssoj_tellig/d6pfv1bg/19/
When I click on the line chart on the point 0.63 at the third week of sample5, I'd like a treemap to appear at the bottom with the values loaded in var mytreemap_data (or any other values for the demo, doesn't matter). I'd like to understand how it'd work.
Many thanks for your help!
var mytreemap_data = [1528675200000,0.1,0.2,0.3,0.15,0.25]
// How can we show a tree map at the bottom with the values above
// upon clicking on the point 0.63 for the third week of sample 5 ??
const chart_1 = new Highcharts.stockChart('mychart_1', {
chart: {
zoomType: 'x',
type: 'spline',
},
xAxis: {
type: 'datetime',
tickInterval: 86400000 * 7, //show each week
ordinal: false,
labels:{
formatter: function() {
return Highcharts.dateFormat('%d %b %Y', this.value);
},
align: 'right',
rotation: -90,
},
},
yAxis: {
opposite: false,
min: 0,
max: 1,
tickInterval: 0.1,
title: {
text: 'Score'
}
},
legend: {
enabled: true,
layout: 'vertical',
align: 'right',
verticalAlign: 'top'
},
credits : {
enabled : false
},
navigator :{
enabled: true
},
scrollbar :{
enabled: true
},
rangeSelector: {
enabled: true,
allButtonsEnabled: true,
buttons: [{
type: 'month',
count: 1,
text: '1m'
}, {
type: 'all',
text: 'All'
}],
selected: 1
},
series: [{
name: 'sample1',
data: [[1527465600000,0.42242020440407213],[1528070400000,0.38747025807155444],[1528675200000,0.42678078180915674],[1529280000000,0.4091743882448146],
[1529884800000,0.4238743811604633],[1530489600000,0.39724984766613747],[1531094400000,0.39441610665405447],[1531699200000,0.41417484302834673],
[1532304000000,0.39208450506752085],[1532908800000,0.4026164523657783]],
}, {
name: 'sample2',
data: [[1527465600000,0.44242020440407213],[1528070400000,0.40747025807155444],[1528675200000,0.44678078180915674],[1529280000000,0.4291743882448146],
[1529884800000,0.4438743811604633],[1530489600000,0.41724984766613747],[1531094400000,0.41441610665405447],[1531699200000,0.43417484302834673],
[1532304000000,0.41208450506752085],[1532908800000,0.4226164523657783]],
}, {
name: 'sample3',
data: [[1527465600000,0.42242020440407213],[1528070400000,0.42747025807155444],[1528675200000,0.46678078180915674],[1529280000000,0.4491743882448146],
[1529884800000,0.4638743811604633],[1530489600000,0.43724984766613747],[1531094400000,0.43441610665405447],[1531699200000,0.45417484302834673],
[1532304000000,0.43208450506752085],[1532908800000,0.4426164523657783]],
}, {
name: 'sample4',
data: [[1527465600000,0.52242020440407213],[1528070400000,0.48747025807155444],[1528675200000,0.52678078180915674],[1529280000000,0.5091743882448146],
[1529884800000,0.5238743811604633],[1530489600000,0.49724984766613747],[1531094400000,0.49441610665405447],[1531699200000,0.51417484302834673],
[1532304000000,0.49208450506752085],[1532908800000,0.5026164523657783]],
}, {
name: 'sample5',
data: [[1527465600000,0.62242020440407213],[1528070400000,0.58747025807155444],[1528675200000,0.62678078180915674],[1529280000000,0.6091743882448146],
[1529884800000,0.6238743811604633],[1530489600000,0.59724984766613747],[1531094400000,0.59441610665405447],[1531699200000,0.61417484302834673],
[1532304000000,0.59208450506752085],[1532908800000,0.6026164523657783]],
}],
plotOptions: {
series: {
label: {
connectorAllowed: false,
},
pointstart: 1527465600000,
// pointInterval = 2,
tooltip: {
valueDecimals: 2
},
}
},
responsive: {
rules: [{
condition: {
maxWidth: 500
},
}]
}
});
document.getElementById('button').addEventListener('click', e => {
var series = chart_1.series[0];
var series1 = chart_1.series[1]
var series2 = chart_1.series[2];
if (series.visible & series1.visible & series2.visible) {
series.hide();
series1.hide();
series2.hide();
e.target.innerHTML = 'Show samples 1-3';
} else {
series.show();
series1.show();
series2.show();
e.target.innerHTML = 'Hide samples 1-3';
}
})
Use click event callback function for a point and create another chart with treemap series, for example:
plotOptions: {
series: {
point: {
events: {
click: function() {
Highcharts.chart('treemapContainer', {
series: [{
type: 'treemap',
data: mytreemap_data
}]
})
}
}
},
...
}
}
Live demo: https://jsfiddle.net/BlackLabel/rh7cfxLj/
API Reference: https://api.highcharts.com/highcharts/plotOptions.series.point.events.click

Flot line chart with categories not working

I have a flot chart with the following code:
var options = {
lines: {
show: true
},
points: {
show: true
},
xaxis: {
tickSize: 1,
mode: "categories"
}
};
var data = [];
data.push(
{"label": "Agrobiodiversity for consumption",
"data": [["January", 3.0], ["February", 3.9], ["March", 2.0], ["April", 1.2], ["May", 1.3], ["June", 2.5],
["July", 2.0], ["August", 3.1], ["September", 2.9], ["October", 0.9],["November", 0.5],["December", 1.8]]});
$.plot($("#flot-dashboard-chart"), data, options);
But I I get:
I have tried addigng the categories in the axis options but nothing seem to work.
Any idea what else do I need to add or what do I need to correct?
U can use my high chart, and u can remove unnecessary stuffs.
Demo with jsFiddle
var chart = Highcharts.chart('container', {
chart: {
type: 'bar'
},
title: {
text: ''
},
subtitle: {
text: ''
},
xAxis: {
labels: {
formatter: function() {
var link_array = ["first", "second", "third", "fourth"];
i = 0;
if (this.value == 'Sugammadex and related compounds')
return '' + this.value + '';
if (this.value == 'Cyclodextrin enabled diclofenac injection (generic Dyloject)')
return '' + this.value + '';
if (this.value == 'Cyclodextrins in biological products')
return '' + this.value + '';
if (this.value == 'Cyclodextrins as a new class of antibiotics')
return '' + this.value + '';
},
useHTML: true
},
categories: ['Sugammadex and related compounds',
'Cyclodextrin enabled diclofenac injection (generic Dyloject)', 'Cyclodextrins in biological products',
'Cyclodextrins as a new class of antibiotics'
],
title: {
text: null
}
},
yAxis: {
labels: {
formatter: function() {
var x_text = ["", "Feasibility study", "Lead / formulation Optimization", "Product Development", "Final product"];
return x_text[this.value];
}
},
title: {
text: '',
align: 'high'
},
tickInterval: 1
},
tooltip: {
formatter: function() {
var x_text = ["", "Feasibility study", "Lead / formulation Optimization", "Product Development", "Final product"];
return x_text[this.y];
}
},
plotOptions: {
bar: {
dataLabels: {
enabled: false
}
}
},
credits: {
enabled: false
},
series: [{
showInLegend: false,
data: [1, 2, 3, 4]
}]
});
$(document).ready(function() {
$("a").on('click', function(event) {
if (this.hash !== "") {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function() {
window.location.hash = hash;
});
}
});
});
Well the "categories" mode is a plugin that need to be loaded in the HTML

Javascript variable with Comma separated values not working in HighChart

I have been using highchart for graphical display of my records. HighChart works fine with my php variable with comma separated values in it. However, I couldn't get this done using javascript variable with comma separated values. Please help me with this. Your help is much appreciated. Thanks. My codes are shown below.
Javascript
<script type="text/javascript">
var res = [];
var data_graph = [];
function show_graphics(){
$.post("<?php echo base_url(); ?>main_controller/show_monthly_analytics_ajax", '', function(data){
if( data.notify == "Success" ){
Object.keys(data.upload_data).forEach(function(key) {
res.push(data.upload_data[key]);
});
data_graph = res.join(",");
console.log(data_graph );
} else{
console.log(data.notify);
}
},'json');
$('#container').highcharts({
chart: {
type: 'column',
margin: 75,
options3d: {
enabled: true,
alpha: 10,
beta: 25,
depth: 70
}
},
title: {
text: '3D chart with null values'
},
subtitle: {
text: 'Notice the difference between a 0 value and a null point'
},
plotOptions: {
column: {
depth: 25
}
},
xAxis: {
categories: Highcharts.getOptions().lang.shortMonths
},
yAxis: {
title: {
text: null
}
},
series: [{
name: 'Sales',
data: [data_graph]
}]
});
}
</script>
When I look at the console, the values being showed of the variable array data_graph seems right but the chart never showed a graph. What is the problem with this?
Modification
<script type="text/javascript">
var res = [];
function show_graphics(){
$.post("<?php echo base_url(); ?>main_controller/show_monthly_analytics_ajax", '', function(data){
if( data.notify == "Success" ){
Object.keys(data.upload_data).forEach(function(key) {
res.push(data.upload_data[key]);
});
//aa = res.join(",");
console.log(res);
} else{
console.log(data.notify);
}
},'json');
$('#container').highcharts({
chart: {
type: 'column',
margin: 75,
options3d: {
enabled: true,
alpha: 10,
beta: 25,
depth: 70
}
},
title: {
text: '3D chart with null values'
},
subtitle: {
text: 'Notice the difference between a 0 value and a null point'
},
plotOptions: {
column: {
depth: 25
}
},
xAxis: {
categories: Highcharts.getOptions().lang.shortMonths
},
yAxis: {
title: {
text: null
}
},
series: [{
name: 'Sales',
data: [res]
}]
});
}
</script>
Response
The data part/section for series property should be an array of numbers.
According to your explanation, your implementation is as if you would have the following:
series: [{
name: 'Sales',
data: ['1, 2, 1, 0'] // this is an array with one string element, which is wrong
}]
But, it should be:
series: [{
name: 'Sales',
data: [1, 2, 1, 0]
}]
See JSfiddle demo here
EDIT
Besides the change that I suggested above, consider that the $.post call is an async execution. Then, you should only draw the chart when data is 'ready' by moving $('#container').highcharts(...) block inside the success callback as follows:
if( data.notify == "Success" ){
Object.keys(data.upload_data).forEach(function(key) {
res.push(data.upload_data[key]);
});
$('#container').highcharts({
...
...
series: [{
name: 'Sales',
data: res
}]
});
} else {
console.log(data.notify);
}

How to configure Highcharts so that it displays some pre-defined value

I have been searching and struggling to find a solution for my problem for a long time but no luck.
I have a simple screen where i ask user to enter their score. Once they enter their score my graph shows up with my pre-defined average score and highest score. In this case, my average score is 1450 and the highest score is 1900.
What i want to do is that once my page is loaded i want my graph displays the average and highest score already. Once user enter his score then it shows up.
Below is my code and you can see it here: http://jsfiddle.net/8jomr1wd/
Any idea?
$(function () {
$('#btn').click(function () {
var val1,
options;
val1 = parseFloat($('input[name=entered]').val());
if ((val1 >= 0) && (val1 <= 1900)) {
// start creating the chart
options = {
chart: {
type: 'column'
},
title: {
text: 'Title'
},
subtitle: {
text: 'This is subtitle'
},
xAxis: {
type: 'category',
labels: {
enabled: true
},
legend: {
enabled: true
},
categories: ['Your score', 'Average', 'Highest Score']
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderColor: '#000000',
borderWidth: 1,
dataLabels: {
enabled: true
},
colorByPoint: true
}
},
credits: {
enabled: false
},
yAxis: {
max: 1900,
tickInterval: 100,
title: 'test'
},
tooltip: {
enabled: true
},
series: [{
name: 'Score',
data: [val1, 1450, 1900]
}],
};
} else {
$("#result").append("<div>Score must be between 0-1900</div>");
}
$('#container').highcharts(options);
})
});
$(document).ready(function () {
$(function () {
create(0)
$('#btn').click(function () {
var val1,
options;
val1 = parseFloat($('input[name=entered]').val());
create(val1);
});
});
});
function create(val1){
if ((val1 >= 0) && (val1 <= 1900)) {
// start creating the chart
options = {
chart: {
type: 'column'
},
title: {
text: 'Title'
},
subtitle: {
text: 'This is subtitle'
},
xAxis: {
type: 'category',
labels: {
enabled: true
},
legend: {
enabled: true
},
categories: ['Your score', 'Average', 'Highest Score']
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderColor: '#000000',
borderWidth: 1,
dataLabels: {
enabled: true
},
colorByPoint: true
}
},
credits: {
enabled: false
},
yAxis: {
max: 1900,
tickInterval: 100,
title: 'test'
},
tooltip: {
enabled: true
},
series: [{
name: 'Score',
data: [val1, 1450, 1900]
}]
};
} else {
$("#result").append("<div>Score must be between 0-1900</div>");
}
$('#container').highcharts(options);
}

Categories