ChartJS dynamically adding values with jQuery array - javascript

I am trying to populate a piechart in ChartJS dynamically using data from a jQuery/AJAX query.
The only thing I am struggling with is creating the data in a format that chartJS understands. This is the required format:
var dynamicData = [
{ label: "One", value: 23 },
{ label: "Two", value: 33 },
{ label: "Three", value: 43 },
{ label: "Four", value: 53 },
]
When I try to create it, I get double quotes "" around each set of data. I know it is a simple mistake but I can't figure it out. This is how I am creating the data (partial jQuery code):
.success(function(response) {
if(!response.errors && response.result) {
var doughnutData = [];
$.each(response.result, function( index, value) {
doughnutData.push('{ label: "'+value[0]+'", value: '+value[2]+',color:"#F7464A" }');
});
console.log(doughnutData);
var doughnutOptions = {
segmentShowStroke : true,
segmentStrokeColor : "#fff",
segmentStrokeWidth : 2,
percentageInnerCutout : 50,
animation : true,
animationSteps : 100,
animationEasing : "easeOutBounce",
animateRotate : true,
animateScale : true,
onAnimationComplete : null
}
var ctx = document.getElementById("chart3").getContext("2d");
var mydoughnutChart = new Chart(ctx).Doughnut(dynamicData, doughnutOptions);
} else {
alert("error");
}
The console shows:
["{ label: "17x1p14e6662", value: 16,color:"#F7464A" }", "{ label: "8734hjgfd784ew", value: 8,color:"#F7464A" }"]
What am I doing wrong?

The console is outputting the object as a string because you are pushing a string to the var doughnutData, you are doing this wrapping the object in quotes and concatenating the values to the string therefor treating the argument passed to the push method as a string type.
The proper way to use the push method to add an object to an array would be like this.
array.push({property:'string', property:2})
Meaning your code should look like this.
doughnutData.push({ label:value[0], value:value[2],color:"#F7464A" });
Here is a link on how the push method works on an array and Here is another link to javascript objects
Another thing is when you are creating the chart your are passing the var dynamicData instead of your var doughnutData.

Related

Chart.js dinamically populate data in Oracle Application Express

Hi I am suing the library chart.js 2.7 with Oracle application express and I am facing issue with passing data array.
I set up same variable fields to store the the array for the chart, but the chart is not displayed/rendered.
note: P79_.. are item of the page (text field) containing the array from ad hoc queries.
Any suggestions? thanks in advance
here's my code
<script>
var BUDGET1 =[document.getElementById("P79_BUDGET1_AC").value]
var BUDGET2 =[document.getElementById("P79_BUDGET2_AC").value]
var ACTUAL1 =[document.getElementById("P79_ACTUAL1_AC").value]
var ACTUAL2 =[document.getElementById("P79_ACTUAL2_AC").value]
new Chart(document.getElementById("mixed-chart"), {
type: 'bar',
data: {
labels: ["P01", "P02", "P03", "P04","P05", "P06", "P07", "P08", "P09", "P10", "P11", "P12"],
datasets: [{
label: "Plan1",
type: "line",
borderColor: "#c45850",
data: BUDGET1,
fill: false
}, {
label: "Plan2",
type: "line",
borderColor: "#3e95cd",
data: BUDGET2,
fill: false
}, {
label: "Actual1",
type: "bar",
backgroundColor: "#ffbb99",
backgroundColorHover: "#ff9933",
data: ACTUAL1,
}, {
label: "Actual2",
type: "bar",
backgroundColor: "#99ffbb",
backgroundColorHover: "#00ff40",
data: ACTUAL2
}
]
},
options: {
title: {
display: true,
text: 'Plan Trend'
},
tooltips: {
callbacks: {
// this callback is used to create the tooltip label
label: function(tooltipItem, data) {
// get the data label and data value to display
// convert the data value to local string so it uses a comma seperated number
var dataLabel = data.labels[tooltipItem.index];
var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].toLocaleString();
// make this isn't a multi-line label (e.g. [["label 1 - line 1, "line 2, ], [etc...]])
if (Chart.helpers.isArray(dataLabel)) {
// show value on first line of multiline label
// need to clone because we are changing the value
dataLabel = dataLabel.slice();
dataLabel[0] += value;
} else {
dataLabel += value;
}
// return the text to display on the tooltip
return dataLabel;
}
}
},
legend: { display: true}
}
});
</script>
I do not know if these instructions to create these arrays works. Could try to use console.log in these values to check if works?
var BUDGET1 =[document.getElementById("P79_BUDGET1_AC").value]
var BUDGET2 =[document.getElementById("P79_BUDGET2_AC").value]
console.log(BUDGET1);
console.log(BUDGET2);
var ACTUAL1 =[document.getElementById("P79_ACTUAL1_AC").value]
var ACTUAL2 =[document.getElementById("P79_ACTUAL2_AC").value]
console.log(ACTUAL1);
console.log(ACTUAL2);
*You can execute this code on console. On chrome press F12, go to console.
Look at this post to see how convert a string with commas to array. Convert string with commas to array

Where to add and register the custom attributes in flot-pie chart js?

Although this question has answer at: Adding custom attributes to flot data
but I have tried every possible way but my custom attributes are not showing on click event.
So far I tried this:
html:
<div id="audit_status" class="chart"></div>
JS:
var audit_status = [
{label: "Pending", data: 2, location_value="Majiwada,Pune"},
{ label: "Ongoing", data: 1 location_value="Mumbai"},
];
var options = {
series: {
pie: {
show: true,
label: {
show: true,
radius: 120,
formatter: function (label, series) {
return '<div style="border:1px solid grey;font-size:8pt;text-align:center;padding:5px;color:white;background-color: #90bdce;">' +
label + ' : ' +
series.data[0][1] +
' ('+Math.round(series.percent)+' %)</div>';
},
background: {
opacity: 0.8,
color: '#000'
}
}
}
},
legend: {
show: true
},
grid: {
hoverable: true,
clickable: true
}
};
$("#audit_status").bind("plotclick", function(event, pos, obj) {
console.log(obj);
//alert(obj.series.value);
if (obj) {
alert(obj.series.location_value);
}
});
$(document).ready(function () {
$.plot($("#audit_status"), audit_status, options);
});
The problem is: whenever I click the pie segment I want to alert "location_value"
but i am getting [Object Object]
I see two issues with the code as it is now. First, the audit_status JSON object isn't quite defined right. The location_value properties need to use colons, not equal signs:
var audit_status = [
{ label: "Pending", data: 2, location_value: "Majiwada,Pune" },
{ label: "Ongoing", data: 1, location_value: "Mumbai" }
];
Second, in your plotclick function, the extra properties defined in your data object don't make it over to the series object passed into the callback. You need to reference the original data object, using the obj.seriesIndex provided to the callback. This JSFiddle provides an example of the code below.
var data = [{
label: "Yes",
data: 50,
location_value: 'Majiwada,Pune'
}, {
label: "No",
data: 150,
location_value: 'Mumbai'
}];
// plot initialization code here
$("#pie").bind("plotclick", function(event, pos, obj) {
if (obj) {
// use the obj.seriesIndex to grab the original data object,
// then you can use any property you defined on that object
alert(data[obj.seriesIndex].location_value);
}
});

Dynamically create parameter from array in jQuery

I'm using this plugin on my website, which works great. You can pass a parameter for state specific styles, it looks like this:
$('#map').usmap({
showLabels: false,
stateStyles: {
fill : '#ffffff',
stroke : '#4f4f4f',
'stroke-width' : 4,
},
stateHoverStyles: {
fill : '#ffffff'
},
stateSpecificStyles: {
'IN': {
fill : '#84b8e7'
},
'CA': {
fill : '#84b8e7'
},
'TX': {
fill : '#84b8e7'
}
},
stateSpecificHoverStyles: {
'IN': {
fill : '#0972ce'
},
'CA': {
fill : '#0972ce'
},
TX': {
fill : '#0972ce'
}
}
});
I would like to fill in those state styles dynamically from an array that looks like ["CA", "IN", "TX"]. Is this possible?
If you're just looking for a way to create an object that looks like that, this snippet will do it for you. Let us know more about what you have/need, and I can expand this.
var arr = ['CA', 'IN', 'TX'], // Your state vars
output = [];
arr.forEach(function(el) {
output[el] = {
fill: '#000000' // Could come from the same array, if needed
};
)};
console.log(output);

How can i access to object elements in javascript?

I'am using the jQuery Gantt api, and I want to access to certain elements, but I don't know how.
$(function() {
"use strict";
//var obj = JSON.parse($(".gantt").gantt);
$(".gantt").gantt({
source: [{
name: "Sprint 0",
desc: "Analysis",
values: [{
from: "/Date(1320192000000)/",
to: "/Date(1322401600000)/",
label: "Requirement Gathering",
customClass: "ganttRed"
}]
}],
navigate: "scroll",
scale: "weeks",
maxScale: "months",
minScale: "days",
itemsPerPage: 10,
onItemClick: function(data) {
alert("Item clicked - show some details");
},
onAddClick: function(dt, rowId) {
alert("Empty space clicked - add an item!");
},
onRender: function() {
if (window.console && typeof console.log === "function") {
console.log("chart rendered");
}
}
});
//alert("OK");
//var parsedData = JSON.parse();
//alert($(".gantt").gantt.source);
$(".gantt").popover({
selector: ".bar",
title: "I'm a popover",
content: "And I'm the content of said popover.",
trigger: "hover"
});
prettyPrint();
});
I found this ape with static example, but am trying to draw my own chart by changing content of element source.
so can some tell me how can i get the element source from the gantt object.
Do you expecting this?
To access gantt elements through object try like this.
var ganttObj = $(".gantt").data("gantt");
Or try to create instance for your gantt like this.
var ganttObj = $(".gantt").gantt("instance");
ganttObj.model.maxScale = "years" //To change `maxScale` property values dynamically
Or you can also directly access your elements like this.
For eg: To change maxScale value from months to years, you can use like below.
$(".gantt").gantt({ maxScale: "years" });
Please let me know if this helps you.
Based on your example, you could simply move the source data into a variable so you can reference it later:
var ganttSource = [{
name: "Sprint 0",
desc: "Analysis",
values: [{
from: "/Date(1320192000000)/",
to: "/Date(1322401600000)/",
label: "Requirement Gathering",
customClass: "ganttRed"
}]
}];
$(".gantt").gantt({
source: ganttSource,
...
});
console.log(ganttSource);

javascript associative array, looping, and / or scope issue with Highcharts JSON call

I have a javascript associative array issue, looping issue, and / or scope issue. I'm trying to call data from a postgresql database, parse it, and implement it in a Highchart.
The data consists of five series with five items (columns / fields) each:
[Object, Object, Object, Object, Object]
Opened, the fifth object looks like:
4: Object
acronym: "1"
current: "3.4"
id: 1
name: "a"
pc1: "2.5"
previous: "2.4"
url: "http://myhost:3000/series/1.json"
__proto__: Object
length: 5
__proto__: Array[0]
After parsing, I get a sequence of objects:
[Object]
[Object]
[Object]
[Object]
[Object]
Which consist of the parsed data expect, i.e., a k:v pair [name: "a", y: 2.5]:
[Object]
0: Object
name: "a"
y: 2.5
__proto__: Object
length: 1
__proto__: Array[0]
However, what I need is an array of objects:
[{name: "a", y: 2.5}, {name: "b", y: 3.0}, {name: "c", y: 1.0}, {name: "d", y: 2.0}, {name: "e", y: 3.2}]
If I insert "dummy" data - below - the chart renders correctly, so the issue's with my code, specifically, the creation of the array and its availability outside the JSON function.
[{name: 'name1', y: 2.5}, {name: 'name2', y: 4.0}];
Any and all help would be appreciated. Here's the entire javascript code for the Highchart - with notes where the issues are.
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container',
type: 'column',
},
title: {
text: 'The Conference Board'
},
legend: {
enabled: false
},
subtitle: {
text: 'Leading Indicators '
},
xAxis: {
type: 'category',
labels: {
rotation: -45,
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
},
credits: {
enabled: false
},
yAxis: {
title: {
text: 'Percent Change Year / Year'
},
},
series: [{
data: [] // dummy code inserted here makes the chart render
}]
};
url = "http://myhost:3000/series";
$.getJSON(url, function (series) {
console.log(series); // five series of five k:v pairs each
$.each(series, function(key_i, val_i) { // parsing to a single k:v (name: value) pair
data = []; // I'm trying to create an array of objects // [{},{},{},{},{}]
data.push({ // for insertion into the var options.series.data above
name: val_i.name,
y: parseFloat(val_i.pc1)
});
options.series[0].data = data;
console.log(options.series[0].data); // getting all k:val_i pairs sequentially; however, not as an array of objects
});
options.series[0].data = data;
console.log(options.series[0].data); // only getting the last k:v pair and the chart doesn't render
});
console.log(options.series[0].data); // an empty array []
var chart = new Highcharts.Chart(options);
});
Again, thank you in advance for your help with this. I've been working on it for days.
try
$.getJSON(url, function (series) {
options.series[0].data = $.map(series, function(val) {
return { name: val.name, y: parseFloat(val.pc1) };
});
new Highcharts.Chart(options);
});
Update fix your existing each loop
$.getJSON(url, function (series) {
var data = [];
$.each(series, function(val) {
data.push({ name: val.name, y: parseFloat(val.pc1) });
});
options.series[0].data = data;
new Highcharts.Chart(options);
});
I believe something like:
var jsonArray = yourArray.map(function(item) { return JSON.stringify(item); });
will handle the conversion to JSON for you.

Categories

Resources