Chart.js undefined variable in view - javascript

I want to crate a graph using chart.js and show it in my view. But after parsing the data to the view, it always come with undefined variable (in my case, bulan and pendapatan is undefined).
This is my controller to parse the data
$query = DB::table("transaksipenjualan")->select(DB::raw('EXTRACT(MONTH FROM tanggaltransaksi) AS Bulan, SUM(total) as Pendapatan'))
->where('tanggalTransaksi', 'LIKE', '%'.$request->tahun.'%')
->groupBy(DB::raw('EXTRACT(MONTH FROM tanggaltransaksi)'))
->get();
$count=count($query);
$label = [];
$data = [];
for($i=0;$i<$count;$i++)
{
$label[$i] = $query[$i]->Bulan;
$data[$i] = $query[$i]->Pendapatan;
}
return view('printPreview/pendapatanBulanan', ['data'=>$query, 'bulan'=>$label, 'pendapatan'=>$data]);
And this is my script to get the data
var ctx = document.getElementById("canvas").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: bulan,
datasets: [{
label: 'Nilai Pendapatan',
data: pendapatan,
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
I don't know very well how to pass the data to a script, so I need some advice. Thanks!

Have you tried using {{ json_encode($php_variable) }}? For example:
var ctx = document.getElementById("canvas").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: {{ json_encode($bulan) }},
datasets: [{
label: 'Nilai Pendapatan',
data: {{ json_encode($pendapatan) }},
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});

Related

How to use a Data Array within a Chart JS dataset?

I have the following JSON, that I want to insert a chart using Chart JS:
{"Results":[{"Data":"25/02/2021","Valor":18},{"Data":"24/02/2021","Valor":2993},{"Data":"23/02/2021","Valor":1936},{"Data":"22/02/2021","Valor":1844},{"Data":"21/02/2021","Valor":1114},{"Data":"20/02/2021","Valor":1060},{"Data":"19/02/2021","Valor":1134}]}
And I created a function to load this JSON into an Array:
function ShowData(jsonObj) {
var bases = jsonObj['Results'];
var Date = [];
var Val = [];
for (var i = bases.length-1; i >= 0; i--) {
Date.push([bases[i].Data]);
Val.push([bases[i].Valor]);
}
}
When I load this Array into the Chart, As below:
var chartGraph = new Chart(ctx,{
type:'line',
data:{
labels: Date,
datasets: [
{
label: "Lbl Name",
data: Val,
borderWidth: 6,
borderColor: 'rgba(77,166,253, 0.85)',
backgroundColor: 'transparent'
}
]
},
options: {
title: {
display: true,
fontSize: 20,
text: 'Chart Name'
},
legend: {
display: true,
position: 'right',
labels: {
fontColor: '#666'
}
}
}
})
No information on "datasets" appears to me, only the "label", what is the mistake I am making?
Graphic Image
Try to split series and data, something like:
function splitData(type) {
return json.Results.map(v => v[type]);
}
// your Chart.js config
data: {
labels: splitData('Date'),
datasets: [
{
// ...otherProps,
data: splitData('Valor')
}
]
}
You cant use Date as variable name since its a build in class. Also from my testing couldnt reference the vars inside the function. But the real problem with your code is that you push an array to the val array. This made it an array containing arrays. This is not supported. If you change your code to the sample below it will work
let date = [];
let val = [];
function ShowData(jsonObj) {
var bases = jsonObj['Results'];
date = [];
val = [];
for (var i = bases.length-1; i >= 0; i--) {
date.push(bases[i].Data);
val.push(bases[i].Valor);
}
}
var chartGraph = new Chart(ctx,{
type:'line',
data:{
labels: Date,
datasets: [
{
label: "Lbl Name",
data: Val,
borderWidth: 6,
borderColor: 'rgba(77,166,253, 0.85)',
backgroundColor: 'transparent'
}
]
},
options: {
title: {
display: true,
fontSize: 20,
text: 'Chart Name'
},
legend: {
display: true,
position: 'right',
labels: {
fontColor: '#666'
}
}
}
})

Charts Js Stacked Bar Graph displays no values?

I have a javascript map like this..
var Severity = {
3M:[0, 3, 1, 0, 0],
5T:[0, 0, 1, 0, 0],
6S:[0, 0, 2, 0, 0]
}
And a JS function to call Stacked Chart Bar. Here I have a created a JS function which takes id and a map from jsp page. Map structure is same as above defined. I want to display graph where in x axis the data is the keys in map and in y axes is the stacked up data of 5 elements.
function StackedBar(id,Severity) {
var label = Object.keys(Severity); // getting the labels
var Critical = [];
var High = [];
var Medium = [];
var Low = [];
var Others = [];
for(let i=0;i<label.length;i++){ //assigning the data to arrays created
Critical.push(Severity[label[i]][0]);
High.push(Severity[label[i]][1]);
Medium.push(Severity[label[i]][2]);
Low.push(Severity[label[i]][3]);
Others.push(Severity[label[i]][4]);
}
var ctxL = document.getElementById(id).getContext('2d'); //id from the html canvas
var chart = new Chart(ctxL, {
type: 'bar',
data: {
labels: label,
datasets: [
{
label: 'Critical',
data: Critical,
backgroundColor: '#aa000e'
},
{
label: 'High',
data: High,
backgroundColor: '#e65905'
},
{
label: 'Medium',
data: Medium,
backgroundColor: '#e00ce6'
},
{
label: 'Low',
data: Low,
backgroundColor: '#b8ab16'
},
{
label: 'Others',
data: Others,
backgroundColor: '#00aaaa'
}
]
},
options: {
responsive: true,
legend: {
position: 'right'
},
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
});
}
Here graph displays and i get label in x axes...but graph values doesn't show and i get following error..
Html
<canvas id="overall"></canvas>
<script>StackedBar('overall',Overall);</script>
I wanted to know what went wrong and want me to help fix this issue...
I put the above together into one file and it works (although I had to change "Overall" to "Severity" in the call). So I'd expect that something you are using might not match your example above.
The version I used:
<html>
<body>
<canvas id="overall"></canvas>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script>
var Severity = {
"3M": [0, 3, 1, 0, 0],
"5T": [0, 0, 1, 0, 0],
"6S": [0, 0, 2, 0, 0]
};
</script>
<script>
function StackedBar(id, Severity) {
var label = Object.keys(Severity); // getting the labels
var Critical = [];
var High = [];
var Medium = [];
var Low = [];
var Others = [];
for (let i = 0; i < label.length; i++) { //assigning the data to arrays created
Critical.push(Severity[label[i]][0]);
High.push(Severity[label[i]][1]);
Medium.push(Severity[label[i]][2]);
Low.push(Severity[label[i]][3]);
Others.push(Severity[label[i]][4]);
}
var ctxL = document.getElementById(id).getContext('2d'); //id from the html canvas
var chart = new Chart(ctxL, {
type: 'bar',
data: {
labels: label,
datasets: [
{
label: 'Critical',
data: Critical,
backgroundColor: '#aa000e'
},
{
label: 'High',
data: High,
backgroundColor: '#e65905'
},
{
label: 'Medium',
data: Medium,
backgroundColor: '#e00ce6'
},
{
label: 'Low',
data: Low,
backgroundColor: '#b8ab16'
},
{
label: 'Others',
data: Others,
backgroundColor: '#00aaaa'
}
]
},
options: {
responsive: true,
legend: {
position: 'right'
},
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
});
}
</script>
<script>StackedBar('overall', Severity);</script>
</html>

Display chartjs bar chart with dynamic data

I need to display a bar chart that I must make with chartJs with dynamic data, I get these dynamic data from an xml link.
I work with two datafields: TaskName and TaskPercentCompleted
The final result must be something like this:
https://scontent.ftun3-1.fna.fbcdn.net/v/t1.15752-9/67290623_1101713790034749_6213821876259520512_n.png?_nc_cat=107&_nc_oc=AQkVef74ok1IcC0m0ujX4t7c4EhNAEs0C-lejsBTHCj9U2zrFRo2UA_gWnuOeA4ZJco&_nc_ht=scontent.ftun3-1.fna&oh=e8503be685f36c7440362b5a0d3c85f5&oe=5DA3B54E
And this is a part of the xml link:
https://scontent.ftun3-1.fna.fbcdn.net/v/t1.15752-9/66803472_2156647134463530_3324310068698021888_n.png?_nc_cat=100&_nc_oc=AQmuJ-gA1lT7F-whtw329vy_eciZoCWNn5hxCW2Zdp4X_RBfyZknVR1Bza-UF_nDn7s&_nc_ht=scontent.ftun3-1.fna&oh=d6ced2436a0c666be4dfd4fe5138a72f&oe=5DAADE21
I got a code but it doesn't work the way I want, it's regrouping data and I don't want that.
window.addEventListener('load',function() {
var dataURL = _spPageContextInfo.webAbsoluteUrl + "/_api/ProjectData/[en-US]/Tasks?$select=TaskName,TaskPercentCompleted&$filter=ProjectName%20eq%20%27Bay%20Plaza%27%20and%20TaskIsSummary%20eq%20true%20and%20TaskIsProjectSummary%20eq%20false";
$.ajax({
url: dataURL,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data) {
var dataResults = data.d.results;
var itermeidiaryObject = {};
$.each(dataResults, function(key, value) {
var nomTask = value.TaskName;
var epn = value.TaskPercentCompleted;
if (epn != null) {
itermeidiaryObject[epn] = ++itermeidiaryObject[epn] || 1;
}
});
var finalObject = Object.keys(itermeidiaryObject).map(function(key) {
return {
label: itermeidiaryObject[key],
y: key
}
});
var pievalues = finalObject.map(function(value, index) {
return value.y;
});
var labels = finalObject.map(function(value, index) {
return value.label;
});
var colorscheme = colors.slice(0, labels.length);
var ctx = document.getElementById('myChart2').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
data: pievalues,
backgroundColor: colorscheme
}]
},
options: {
responsive: true,
scales: {
xAxes: [{
ticks: {
beginAtZero: true // Edit the value according to what you need
}
}],
yAxes: [{
stacked: true
}]
},
title: {
display: true,
position: "top",
text: "Nombre de projets par direction",
fontSize: 18,
fontColor: "#111"
},
legend: {
display: false
}
}
});
}
});
});
var colors = ["#0074D9", "#FF4136", "#2ECC40", "#FF851B", "#7FDBFF", "#B10DC9", "#FFDC00", "#001f3f", "#39CCCC", "#01FF70", "#85144b", "#F012BE", "#3D9970", "#111111", "#AAAAAA"];
I solved the problem
window.addEventListener('load',function() {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/ProjectData/[en-US]/Tasks?$select=TaskName,TaskPercentCompleted&$filter=ProjectName%20eq%20%27Bay%20Plaza%27%20and%20TaskIsSummary%20eq%20true%20and%20TaskIsProjectSummary%20eq%20false",
method: "GET",
headers: { "Accept": "application/json; odata=nometadata" },
success: function (data) {
if (data.value.length > 0) {
var pieValues = [];
var pieLabels = [];
for (var i = 0; i < data.value.length; i++) {
pieValues.push(parseInt(data.value[i].TaskPercentCompleted));
pieLabels.push(data.value[i].TaskName);
}
var pieData = {
datasets: [{
data: pieValues,
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850","#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850",
"#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850","#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850",
"#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850","#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850",
"#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850","#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850",
"#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850","#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850",
"#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850","#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
}],
labels: pieLabels
};
var ctx = document.getElementById("myChart2");
var myPieChart = new Chart(ctx, {
//type: 'pie',
type: 'bar',
data: pieData,
options: {
responsive: true,
legend: { display: false },
title: {
display: true,
text: 'Nom de tâche par pourcentage'
},
scales: {
xAxes: [{
ticks: {
maxRotation: 90,
minRotation: 90,
display: false
}
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
},
error: function (data) {
//
}
});
});

how get data from given string in javascript?

I am using Laravel 5.6. I am trying to create a line chart graph using CHARTJS.
Here is the controller.
public function index()
{
$currentMonth = date('m');
$category = Category::where('isActive', 1)->count();
$product = Product::where('isActive', 1)->count();
$suppliers = Supplier::where('isActive', 1)->count();
$saleorderCount = SaleOrderDetail::count();
$sale_order_detail = SaleOrderDetail::whereRaw('MONTH(created_at) = ?',[$currentMonth])->get(['sale_order', 'grand_total']);
$data_points = SaleOrderDetail::select('sale_order', 'grand_total')->whereRaw('MONTH(created_at) = ?',[$currentMonth])->get();
$data_points = str_replace('sale_order', 'x', $data_points);
$data_points = str_replace('grand_total', 'y', $data_points);
$data_points = str_replace(',y:', '",y:', $data_points);
dd($data_points);
// dd($sale_order_detail);
return view('welcome', ['category' => $category, 'product' => $product, 'suppliers' => $suppliers, 'salecount' => $saleorderCount, 'sale_order_detail' => $sale_order_detail, 'data_points' => $data_points]);
}
With $data_points, passing value to view. Here is the script
<script type="text/javascript">
window.onload = function () {
var data_point = {!! $data_points !!};
console.log(data_point);
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: data_point,
datasets: [{
label: 'Sale of the Month',
data: data_point,
backgroundColor: [
'rgba(54, 162, 235, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
</script>
here is the console output of data points.
Here it how it show the chart.
Labels are not showing.
You're passing an array of objects for both your labels and your data. You want to pass an array of strings for the labels and an array of numeric values for your data. Change your code to this:
window.onload = function () {
var data_points = {!! $data_points !!};
//create your new arrays here
var data_labels = data_points.map((index) => index.x);
var data_values = data_points.map((index) => parseInt(index.y));
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
//use data_labels array here
labels: data_labels,
datasets: [{
label: 'Sale of the Month',
//use data_values array here
data: data_values,
backgroundColor: [
'rgba(54, 162, 235, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}

chart.js ajax pushing another dataset always "undefined"

Following is my javascript Code, but the only thing really relevant is the last function. I want to update the Chart to add another dataset, without reloading the Page. But for reason the added dataset is always undefined. The commented-out line, which uses the exact same array of data, on the other hand works. Since I'm new to javascript I'm not sure, if I missed something obvious, or if chart.js just doesn't support this kind of thing at all.
const CHART = document.getElementById("lineChart");
var dts1 = [
{
label: "Abfall gesamt",
data: Abfall_gesamt,
}
];
var dts2 = [
{
label: "Abfall schadstoffhaltiger",
data: Abfall_schadstoff,
}
];
var lineChart = new Chart(CHART, {
type: 'line',
data: {
labels: Jahr,
datasets: dts1
}
});
function myFunction(){
//lineChart.data.datasets[0].data = Abfall_schadstoff;
lineChart.data.datasets.push(dts2);
lineChart.update();
}
The issue is, you are defining your datasets (dts1 and dts2) as an array. They should be an object, like so ...
var dts1 = {
label: "Abfall gesamt",
data: Abfall_gesamt,
};
var dts2 = {
label: "Abfall schadstoffhaltiger",
data: Abfall_schadstoff,
};
and then, when generating the chart, set datasets value as ...
datasets: [dts1]
ᴅᴇᴍᴏ
const CHART = document.getElementById("lineChart");
var Abfall_gesamt = [1, 2, 3];
var Abfall_schadstoff = [4, 5, 6]
var dts1 = {
label: "Abfall gesamt",
data: Abfall_gesamt,
backgroundColor: 'rgba(255, 0, 0, 0.2)'
};
var dts2 = {
label: "Abfall schadstoffhaltiger",
data: Abfall_schadstoff,
backgroundColor: 'rgba(0, 0, 255, 0.2)'
};
var lineChart = new Chart(CHART, {
type: 'line',
data: {
labels: ['Jahr', 'Mahr', 'Kadr'],
datasets: [dts1]
},
options: {
responsive: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}]
}
}
});
function myFunction() {
//lineChart.data.datasets[0].data = Abfall_schadstoff;
lineChart.data.datasets.push(dts2);
lineChart.update();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<button id="add" onclick="myFunction()">Add Dataset</button>
<canvas id="lineChart" height="190"></canvas>

Categories

Resources