I need to get graph generated from Mysql database with help of PHP. I got nice application from (http://canvasjs.com). So, I created my own JSON format in variable element from PHP SESSION. It gies me no error when debugged, but no result.
Line number 34 - 37 gives me graph if I don't comment them. When comment them and replace with my own JSON which is variable element and does not give me graph. Gives me blank page.
I am new to JSON. Help me out with this.
Following are my codes.
var array = <?php echo json_encode($_SESSION["r_array"]); ?>;
var count = 0;
var element = '';
var title = 'Malware lab, TCRC, CTA';
for( var i in array) {
if ( count == 0 ) {
element += ‘{y: ‘+array[i]+’,’+’ indexLabel: “‘+i+'”}';
} else {
element += ‘, {y: ‘+array[i]+’,’+’ indexLabel: “‘+i+'”}';
}
count++;
}
var chart = new CanvasJS.Chart(“chartContainer”,
{
title: {
text: title
},
data: [
{ type: type,
dataPoints: [
/*
34 {y: 2, indexLabel: “Kaka'”},
35 {y: 3, indexLabel: “Blackberry”},
36 {y: 1, indexLabel: “Windows Phone”},
37 {y: 5, indexLabel: “Others”},*/
element,
]
}
]
});
chart.render();
Dumped array of $_SESSION["r_array"] as following
Array (
[Trojan] => 1
[Malware] => 3
[Backdoor] => 6
[Virus] => 2
[Bot] => 5
[Rootkit] => 7
[Worm] => 5
)
element must be an array, you are trying to create it as a string(with syntax errors)
var array = <? php echo json_encode($_SESSION["r_array"]); ?> ;
var count = 0;
var element = [];
var title = 'Malware lab, TCRC, CTA';
for (var i in array) {
element.push({
y: array[i],
indexLabel: i
})
count++;
}
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: title
},
data: [{
type: type,
dataPoints: element
}]
});
chart.render();
Demo: Fiddle
Yo need to pass array in correct Way
Use another variable datapoints = [];
and the push object into that array
var datapoints = [];
for( var i in array) {
datapoints.push({ y : array[i] , indexLabel : i});
}
and then use it as below
var chart = new CanvasJS.Chart(“chartContainer”,
{
title: {
text: title
},
data: [
{ type: type,
dataPoints: datapoints
}
]
});
chart.render();
Related
I am trying to create an canvasJS, JavaScript Bar Charts, with the following functions,
var dataPoints = [];
var headers;
var groups = [];
var cityWide = 0;
var chart = createChart();
function createChart(title = "Hospitalized Count") {
return new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title:{
text:"Coronavirus Data in NYC Boroughs"
},
axisX:{
interval: 1
},
axisY2:{
interlacedColor: "rgba(1,77,101,.2)",
gridColor: "rgba(1,77,101,.1)",
title: "Total number of "+title
},
data: [{
type: "bar",
name: "companies",
axisYType: "secondary",
color: "#014D65",
dataPoints: dataPoints
}]
});
}
I am using this function below to set the dataPoints array:
function call: dataPoints = setDataPoints(4)
function setDataPoints(value){
let temp = [];
for(var i = 0; i<groups.length;i++){
if(groups[i][0] == "Citywide"){
continue;
}
yValue = groups[i][value];
myLabel = groups[i][0];
console.log("y: "+ yValue);
console.log("label: "+ myLabel);
temp.push(
{
y: yValue,
label: myLabel
});
}
console.log(temp);
return temp;
}
But when i console.log(dataPoints) I am getting this:
[
{"y": "136319","label": "Bronx","x": 0},
{"y": "202778","label": "Brooklyn","x": 1},
{"y": "97006","label": "Manhattan","x": 2},
{"y": "202737","label": "Queens","x": 3},
{"y": "54479","label": "StatenIsland","x": 4}
]
the expected result for dataPoints should be as follows:
[
{y:136319, label: "Bronx" },
{y:202778, label: "Brooklyn" },
{y:97006, label: "Manhattan" },
{y:202737, label: "Queens" },
{y:54479, label: "StatenIsland" }|
]
When I tried to set x
temp.push(
{
x: "123",
y: yValue,
label: myLabel
});
or delete temp[i]['x'] it doesn't work.
As you may of notice the x value are the indexes of the array, I have no idea why its being set and how do I even remove.
I have tried
dataPoints = temp;
console.log(dataPoints[0].hasOwnProperty('x'));
and returns false
Any help would appreciate it thanks in advance!
EDIT based of comment:
in for loop:
console.log(temp[i]['x']) returns undefined
If I add in to temp.push({ x: "123", ...})
console.log(temp[i]['x']) returns 123
console.log(temp[i]):
{y: "54479", label: "StatenIsland"}
label: "StatenIsland"
x: 4
y: "54479"
__proto__: Object
function.js:98
I'm not familiar with CanvasJS but my guess is that it's mutating the dataPoints array you give it to fill in the 'x' coordinate on the chart. console.log doesn't run synchronously, so by the time you see the output it's already been mutated.
If you console.log([...dataPoints]) or console.log([...temp]) I bet the x won't be there.
According to the API docs for dataPoints.x:
If not provided, it will be set automatically set according to its index position on dataPoints Array.
If you want to keep your "clean" copy of dataPoints you need to pass a copy of the array to the chart [...dataPoints].
for (var i = 0; i < valueInfo.length; i++) {
if (++conteur === valueInfo.length) {
MydataPoints+='{ y: '+parseInt(valueInfo[i])+', indexLabel: "Feminin" }';
}
else {
MydataPoints+='{ y: '+parseInt(valueInfo[i])+', indexLabel: "Feminin" },';
}
}
result of MydataPoints is = ["{ y: 3, indexLabel: "Feminin" },{ y: 5, indexLabel: "Feminin" }"]
But for working chart in need like this array : [{ y: 3, indexLabel: "Feminin" },{ y: 5, indexLabel: "Masculin"}]
Thank you very much for your help.
what you are trying to do is to build JSON string manually, whereas ChartJS required JSON object.
[{ y: 3, indexLabel: "Feminin" },{ y: 5, indexLabel: "Masculin"}]
This is valid JSON string and you are trying to build this manually into JS.
Instead, try fetching data from server itself into JSON format and it will give you proper JSON string,
for your manual operation into JSON you can loop through ajax response or take care for it into server logic.
Still, if you need to work on JS manually, instead of JSON binding try making HTML markup for ChartJS.
Try this:
var valueInfo = ["12","13"];
var MydataPoints = [];
for (var i = 0; i < valueInfo.length; i++) {
MydataPoints.push({
y: parseInt(valueInfo[i]),
indexLabel: "Feminin"
});
};
var div = document.getElementById('text');
div.innerHTML = JSON.stringify(MydataPoints);
<div id="text"></div>
var MydataPoints=[]
if(++conteur === valueInfo.length) {
MydataPoints.push({ y:parseInt(valueInfo[i]), "indexLabel": "Feminin" });
}
else{
MydataPoints.push({ y:parseInt(valueInfo[i]), "indexLabel": "Feminin"}); };
I am having a bit of an issue with the following code:
//The Code:
var data = [];
for (var i = 0; i < mydata.length; i++) { //looping through data received
var obj = mydata[i]; //current obj in loop
var newObj = { //creating new obj with same structure as the 'data' that works
name: obj.name,
y: obj.subhere.subhere1,
id: i
};
data.push(newObj); //pushing each object into the data array
}
//THE DATA:
var data = [{ name: 'Name 1', y: 20, id: 0 },{ name: 'Name 2', y: 10, id: 1 },{ name: 'Name 3', y: 10, id: 2 }];
//THE CHART CODE:
chart = new Highcharts.Chart({
series:[
{
"data": data,
type: 'pie',
animation: false,
point:{
events:{
click: function (event) {
//alert(this.id);
}
}
}
}
],
"chart":{
"renderTo":"container"
},
});
//The above with create a pie chart with 3 names
//The Data
var mydata =[{
"001":{
"name":"Name 1",
"subhere":{
"subhere1":2
}
},
"002":{
"name":"Name 2",
"subhere":{
"subhere1":20
}
},
}];
The console is giving me the following error:
TypeError: obj.subhere is undefined y: obj.subhere.subhere1,
I can see that the subhere.subhere1 names actually exists so in theory it should not be giving me an error, right?.
How can I fix this issue ... any ideas?
myData doesn't look correctly formatted. It has an extra comma after the bracket before last:
},
}];
You can loop through your object properties:
var data = [];
for (var i = 0; i < mydata.length; i++) { //looping through data received
var obj = mydata[i]; //current obj in loop
for(var key in obj){
var newObj = { //creating new obj with same structure as the 'data' that works
name: obj[key].name,
y: obj[key].subhere.subhere1,
id: i
};
data.push(newObj); //pushing each object
}
}
To work with your existing code, you could change the definition of mydata to this:
var mydata =[
{
"name":"Name 1",
"subhere":{
"subhere1":2
}
},
{
"name":"Name 2",
"subhere":{
"subhere1":20
}
}
];
Hi i am getting json array as response of ajax request:
{"chart":{"2016-03-08":"1","2016-03-07":"4","2016-03-06":0,"2016-03-05"
:0,"2016-03-04":0,"2016-03-03":"145","2016-03-02":0}}
Now i want to prepare a chart by giving these values to chart input as below: ( i want output like this from above array )
data: [{
y: '2016-03-07',
a: 100
}, {
y: '2016-03-08',
a: 75
}, {
y: '2016-03-06',
a: 50
}, {
y: '2016-03-05',
a: 75
}, {
y: '2016-03-09',
a: 50
}, {
y: '2016-03-03',
a: 75
}, {
y: '2016-03-02',
a: 180
}
],
I have tried :
var chart_params = {};
for (var key in data_chart) {
let value = data_chart[key];
chart_params = '{ y:'+ key+ ', a: '+value+' }';
}
console.log(chart_params);
but it is not giving output as expected
Try this
data = {"chart":{"2016-03-08":"1","2016-03-07":"4","2016-03-06":0,"2016-03-05" :0,"2016-03-04":0,"2016-03-03":"145","2016-03-02":0}}
var chart_params = [];
data_chart = data.chart;
for (var key in data_chart) {
var value = data_chart[key];
chart_params.push({ y: key, a:value});
}
console.log(chart_params);
jsfiddle: https://jsfiddle.net/hb8qd1p8/1/
#madalin's answer is the correct fix for your issue, though another option to accomplish what you want is to use map:-
var data = {"chart":{"2016-03-08":"1","2016-03-07":"4","2016-03-06":0,"2016-03-05":0,"2016-03-04":0,"2016-03-03":"145","2016-03-02":0}};
var array = Object.keys(data.chart).map(function (key) {
return { y: key, a: data.chart[key] };
});
document.write(JSON.stringify(array, null, 4));
I'm using a bubble chart. I represent "Ideas" in this chart. Each bubble is one specific idea with an X-value and a Y-value. What I need is the "Idea name" in the tooltip for each bubble as additional information.
I already know that you can do it as followed:
series: [{
data: [ { x : 1, y : 100, myIdea : 'Idea1' },
{ x : 2, y : 150, myIdea : 'Idea2' },
{ x : 5, y : 170, myIdea : 'Idea3' } ]
}]
But here comes the problem:
I used an array of this kind before:
dataArray [0][0] = 1; dataArray [0][1] = 100; dataArray [0][2] = 5;
dataArray [1][0] = 2; dataArray [1][1] = 150; dataArray [1][2] = 5;
coming from a loop.
My dataArray array then looked like that: [1,100,5], [2,150,5], ...
I gave that to the series like that:
series: [{
data: dataArray
}]
that worked perfectly!
How do I create an array in this expected format:
data: [ { x : 1, y : 100, myIdea : 'Idea1' },
{ x : 2, y : 150, myIdea : 'Idea2' },
{ x : 5, y : 170, myIdea : 'Idea3' } ]
Does this somehow work with associative arrays like that:
var myData= {
"x": "1",
"y": "100",
"myIdea": "idea1"
}
Btw, what is the best way to pass dynamic data for the bubblechart series?
You can loop over your current dataArray and build the new array like so:
var oldDataArray = [
[1, 100, 5],
[2, 150, 5]
];
var newDataArray = oldDataArray.map(function (row) {
return {
x: row[0],
y: row[1],
z: row[2]
};
});
console.log(newDataArray);