How to add an array of objects to chartjs? - javascript

How to add an array of objects to chartjs.The controller of that view sends to the template twig an array through the variable {{cg}}. The way I am doing it I get an error that what I'm going through is an array of array. In the labels attribute I want put the arrangement of months and in the attribute data the fix of imp. Please have any idea of ​​this? Controller:
/** Controller
* #Route("/cg1", name="cg1")
*/
public function cg1Action()
{
$conn=$this->get('database_connection');
$consulta="SELECT consumo_combustible.importe as imp,MONTH(consumo_combustible.fecha) as mes FROM consumo_combustible WHERE YEAR(consumo_combustible.fecha)=2018";
$sql=$conn->fetchAll($consulta);
return $this->render('default/consultag1.html.twig', array('cg' => $sql));
}
//--------------
//- AREA CHART -
//--------------
// Get context with jQuery - using jQuery's .get() method.
var areaChartCanvas = $('#areaChart').get(0).getContext('2d')
// This will get the first returned node in the jQuery collection.
var areaChart = new Chart(areaChartCanvas)
var datames = []
datames={{ cg.mes }} ;
var dataimp = [] ;
dataimp={{ cg.imp }} ;
var areaChartData = {
labels : datames,
datasets: [
{
label : 'Electronics',
fillColor : 'rgba(210, 214, 222, 1)',
strokeColor : 'rgba(210, 214, 222, 1)',
pointColor : 'rgba(210, 214, 222, 1)',
pointStrokeColor : '#c1c7d1',
pointHighlightFill : '#fff',
pointHighlightStroke: 'rgba(220,220,220,1)',
data : dataimp
},
{
label : 'Digital Goods',
fillColor : 'rgba(60,141,188,0.9)',
strokeColor : 'rgba(60,141,188,0.8)',
pointColor : '#3b8bba',
pointStrokeColor : 'rgba(60,141,188,1)',
pointHighlightFill : '#fff',
pointHighlightStroke: 'rgba(60,141,188,1)',
data : dataimp
}
]
}
throws the following error:
Key "mes" for array with keys "0, 1, 2, 3, 4, 5" does not exist in default\consultag1.html.twig at line 55

Related

how to get data from SQL using php to represent on chartjs

I'm using chartjs.org in order to display my records from database to line chart. However, i'm novice for Javascript so i'm unable to retrieve the data to the line chart.
This is what i wanted to do:
I have a table called daily_price having (supplying company, date and price) column. Now every time when i entered a new record, i want to update the line chart x and y axis to represent the new date on the x axis and the price on the y axis with out loosing its previous price on the chart.
I have already implemented the table and the chart, but i can't able to change the default js data read from database.
<script src="../administrator/js/chart.min.js"></script>
<script type="text/javascript">
var randomScalingFactor = function(){ return };
var lineChartData = {
labels : ["Jan","Feb","March","April","May","June","July","Aug","Sept","Oct","Nov","Dec"],
datasets : [
{
label: "My Second dataset",
fillColor : "rgba(48, 164, 255, 0.2)",
strokeColor : "rgba(48, 164, 255, 1)",
pointColor : "rgba(48, 164, 255, 1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(48, 164, 255, 1)",
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
}
]
}
window.onload = function(){
var chart1 = document.getElementById("line-chart").getContext("2d");
window.myLine = new Chart(chart1).Line(lineChartData, {
responsive: true
});
};
</script>
So how to change the labels and the data section that will represents the price and the date respectively.
Its really appreciated If any one can help me with this.
Thanks!

Chart not rendered properly while using Chart.js

I am using Chart.jsenter link description here to draw a Line graph. Problem is with one of the data sets. The max value becomes 8 instead of 128 when I add the third data set with the variable.
datasets : [
{
fillColor : "#1abc9c",
strokeColor : "#1abc9c",
pointColor : "#1abc9c",
pointStrokeColor : "#fff",
data : response.countStart
},
{
fillColor : "#3498db",
strokeColor : "#3498db",
pointColor : "#3498db",
pointStrokeColor : "#fff",
data : response.countSeen
},
{
fillColor : "#e67e22",
strokeColor : "#e67e22",
pointColor : "#e67e22",
pointStrokeColor : "#fff",
data: response.countClicked
//data : [0, 0, 10, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 6, 11, 15, 20, 2]
}
]
I have three datasets and I get them with AJAX and create the chart when i receive the response. Problem occures when I add the last data set to the array. ("response.countClicked") The commented line is that array actually. It is ok when I use it hardcoded but there is a problem when I use that variable. Also it is ok when I use the other variables like response.countSeen or response.countStart at the 3rd data set
I made a work around with options and it rendered as I wanted. I created options and used it while creating the chart and it worked.
// getting the most possible array that contains the max value
var max = Math.max.apply(Math, response.countSeen);
var steps = max / 10;
var options = {
scaleOverride: true,
scaleSteps: steps,
scaleStepWidth: 10,
scaleStartValue: 0
};

Rendering Ember component (google line chart) with rails backend

Recently I started a project with rails backend and ember js, however I find the documentation on both together is difficult to find or quite ambiguous, however I have parts of my app working perfectly.
Now, I decided to code a google line chart in an ember component. With ember inspector, it tends to throw an error on localhost:3000/#/chart currently the error:
Uncaught Error: <Sample.ChartView:ember526> Handlebars error: Could not find property 'chart' on object (generated chart controller)
So, here's my code for the relevant files:
assets/javascript/components/chart_component.js:
var data = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : [51,10,18,58,65,95,87]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : [28,48,40,19,96,27,100]
}
]
};
var data2 = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : [51,10,18,58,65,95,87]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : [28,48,40,19,96,27,100]
}
]
};
Sample.LineChartComponent = Ember.Component.extend({
tagName: 'canvas',
attributeBindings: ['width', 'height'],
width: '480',
height: '360',
data: null,
didInsertElement: function() {
var ctx = this.get('element').getContext("2d");
var myNewChart = new Chart(ctx).Line(this.get('data'));
}
});
javascripts/routes/chart_route:
Sample.ChartRoute = Ember.Route.extend({
model: function(){
return Ember.Object.create({
modelOne: data,
modelTwo: data2
});
}
});
Where I'm calling the chart component.. javascripts/templates/chart.handlebars
<h2>Chart one</h2>
{{chart data= model.modelOne}}
<h2>Chart two</h2>
{{chart data= model.modelTwo}}
As for the naming convention:
Components must have a dash in their name. So blog-post is an
acceptable name, but post is not. This prevents clashes with current
or future HTML element names, and ensures Ember picks up the
components automatically.
http://emberjs.com/guides/components/defining-a-component/
As far as I see, you called your component simply "charts", that might be the problem.

creating a multidimensional array and fill it

I want to draw a graph on my page and would like to use Charts.js. The Documentation on
http://www.chartjs.org/docs/
says that the Chars I want to create needs an Array of Labels like this:
var data = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : [65,59,90,81,56,55,40]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : [28,48,40,19,96,27,100]
}
]
}
Question: How do I create such a Array?
Question: How can I fill this array with the Input of a Textfield?
Thanks!
Jan
A1) The way you have written is the right way to create arrays in javascript
A2) Suppose you have a textfield with id='month'. You can access its value like this:
var month = document.getElementById('month').value
Next you can create an array var label = []; and add the data from the text field by pushing in the array. i.e label.push(month)
Once you have populated the array for label, you can assign this array to property labels of your data object.
Similarly to assign values to data, create an array var values = []; var values2 = []; Now populate the values and values2 array by pushing values into it.
var label = [];
var values = [];
var values2 = [];
var month = document.getElementById('month').value;
//keep on doing this for all input fields
label.push(month)
//similarly push data into values and values2.
//Now build your structure for chart as follows:
var data = {
labels : label,
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : values
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : values2
}
]
}
Here label , values and values2 are the arrays you got from your textfields.
Hope this helps.
define something like this{
data = {
label:""
fields: [],
};
push the value
data.fields.push({
label: "label",
value: "your constructed value"
});

Why do literal arrays work, but not coded arrays?

I am trying to use Chart.js. If I pass the chart creator the example code:
var data = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : [65,59,90,81,56,55,40]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : [28,48,40,19,96,27,100]
}
]
}
It works fine. However, when I try and pass it this object:
function ChartDataObject(labels, datasets)
{
this.labels = Array();
this.datasets = Array();
this.datasets = datasets;
this.labels = labels;
}
Where labels and datasets are arrays and arrays of arrays, respectively. Both labels and datasets both show:
[object Element], [object Element], etc
When I alert them as follows:
alert(labels);
alert(datasets);
I know that they are filled with string values, and the number of elements in them is correct. Is there something that I am missing in order for Chart.js to see them the same way it sees the data object? I should note, that the Chart.js does generate, however the labels all read [object Element] and the data does not show (Because it thinks that it is [object Element] instead of a number I think).
How do I convert the coded arrays to work the same as the literal created arrays?
EDIT:
dataset Object:
function Dataset(webrequest, fillColor, strokeColor)
{
this.webrequest = webrequest;
this.fillColor = fillColor;
this.strokeColor = strokeColor;
this.data = Array();
}
dataset.data filling:
var valuesArray = xmlDoc.getElementsByTagName("value");
for (var i = 0; i < valuesArray.length; i++)
{
that.datasets[a].data[i] = valuesArray[i];
}
It seems likely that whatever you are passing to your constructor for labels and data is not in the correct form. For us to help identify exactly what your issue is, you will have to show us the code you are using to create those data structures.
If you do it like this, it will reproduce what was in the sample code:
// array of names
var names = ["January","February","March","April","May","June","July"];
// array of objects
var items = [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : [65,59,90,81,56,55,40]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : [28,48,40,19,96,27,100]
}
];
function ChartDataObject(labels, datasets)
{
this.datasets = datasets;
this.labels = labels;
}
var obj = new ChartDataObject(names, items);
// now obj should be in the same form as the data variable in the sample code

Resources