how get data from given string in javascript? - 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
}
}]
}
}
});
}

Related

How can i display all the data from a data table in the Pie Chart.js?

I have this task where i have to display all the data from the table which i will provide it with an image, but i can only display the data that are shown in the data table when the pagination is: false. I need to display all the data when the pagination is: true.
This is the image display
<input class="form-control-xs" type="date" id="start" onchange="table.column(3).search(this.value).draw();">
<script>
'use strict'
let url='{{ $objApi }}';
let columnDef=[
{"title":"ID","data":"0"},
{"title":"Method","data":"1"},
{"title":"Path","data":"2"},
{"title":"Date","data":"3"},
{"title":"Counter","data":"4"}
];
let table=$('#adminuser').DataTable({
columns: columnDef,
processing: true,
serverSide: true,
paging: true,
ajax: {
'url': url,
'method': 'GET'
},
"searchCols": [
null,
null,
null,
{"search": currentDate},
null
],
"order": [[4, 'desc']],
language: {
searchPlaceholder: 'Search...',
sSearch: '',
lengthMenu: '_MENU_ items/page',
},
});
</script>
var ctx = document.getElementById("canvas").getContext("2d");
const data = {
labels: [],
datasets: [{
label: 'Counter',
data: [],
backgroundColor: [
'rgba(90, 57, 228, 0.7)',
'rgba(84, 73, 44, 1)',
'rgba(143, 105, 20, 0.1)',
'rgba(74, 3, 153, 0.1)',
'rgba(81, 35, 162, 0.6)'
]
}]
};
let mychart = new Chart(ctx, { type: 'pie', data: data, options: {plugins: {legend: {display: false}}},});
table.on( 'draw', function ()
{
rows=table.rows().data().toArray();
console.log(rows);
let labels=[];
let data=[];
rows.forEach((element) => {
labels.push(element[2] + ' ' + element[1]);
data.push(element[4]);
});
mychart.data.labels = labels;
mychart.data.datasets[0].data = data; // or you can iterate for multiple datasets
mychart.update(); // finally update our chart
} );

How can my Chart.js just update when data in SQL change?

I build a web app in MVC using SignalR to update real-time data. I can display my chart with real-time data from SQL but it just updates by the time set in setInterval. But now I want my chart to just update when my data in SQL SERVER changes. I have tried many ways but it's not correct. Can you help me with the algorithm? Thank you.
Here is my code :
<!--Chart-->
<script>
var ctx = document.getElementById("percent-chart2");
var colorarray = ['#00b5e9', '#fa4251', '#006400'];
var pre_vals = 0;
//
var myVar = setInterval(GetValue, 1000);
function GetValue() {
var val1 = parseFloat(document.getElementById("tblValue").innerHTML);
var val2 = parseFloat(document.getElementById("tblValue1").innerHTML);
var vals = [val1, val2, 2000];
return vals;
}
if (ctx) {
ctx.height = 209;
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
datasets: [
{
label: "My First dataset",
//data: [GetValue, GetValue, GetValue],
data: GetValue(),
backgroundColor: [
'#00b5e9',
'#fa4251',
'#006400'
],
hoverBackgroundColor: [
'#00b5e9',
'#fa4251',
'#006400'
],
borderWidth: [
0, 0, 0
],
hoverBorderColor: [
'transparent',
'transparent',
'transparent'
]
}
],
labels: [
'STATION 1',
'STATION 2',
'STATION 3'
]
},
options: {
maintainAspectRatio: false,
responsive: true,
cutoutPercentage: 57,
animation: {
animateScale: true,
animateRotate: true
},
legend: {
display: false,
position: 'bottom',
labels: {
fontSize: 14,
fontFamily: "Poppins,sans-serif"
}
},
tooltips: {
titleFontFamily: "Poppins",
xPadding: 15,
yPadding: 10,
caretPadding: 0,
bodyFontSize: 16,
}
}
});
}
function UpdateChart(datachart, data, color) {
datachart.data.datasets.pop();
datachart.data.datasets.push({
data: data,
backgroundColor: color,
hoverBackgroundColor: color
});
datachart.update();
}
setInterval(function () {
const my_val = GetValue();
//var updatedata = [my_val, my_val, 2000];
var updatedata = my_val;
UpdateChart(myChart, updatedata, colorarray);
}, 10000);
</script>
The way I handle this is by adding a client call with the dataset after the database update has completed. This way you only update when that update is called.
Here is a rough example off the top of my head:
public void UpdateDB(int updatedData)
{
//DB work to commit the updatedData
....
//Query your dataset into an serialized updatedDataset
....
//Call a method to create an array (updatedColors) of colors based on the the Count of updatedDataset
....
//Send data to client(s)
Clients.All.yourclientfunction(updatedDataset, updatedColors);
}

Passing parameters to linechart angular typescript

I want to pass a parameter to chart line based to json iput s data1 instead of var labeltabmles = ['Redddd', 'Blue', 'Yellow', 'Green'];
var datalabel = [1240, 190, 30, 545];
I did the algorithme below in order to get the values of count on variable listcount and get the values of type on variable listtype to configure parameter labels and data of line chart configuration from json file inputs using the code below :
listcount = [];
listtype = [];
......
ngOnInit(): void {
var data1 = [{
"type": "MATH",
"count": 55
}, {
"type": "ENGLISH",
"count": 22
},
{
"type": "SCINETIST",
"count": 18
}];
for (var key in data1) {
var typeelement = data1[key]["type"];
var countelemtn = data1[key]["count"];
this.listtype.push(typeelement);
this.listcount.push(countelemtn);
console.log(this.listcount);
console.log(this.listtype);
}
console.log(this.listcount);
console.log(this.listtype);
var labeltabmles = ['Redddd', 'Blue', 'Yellow', 'Green'];
var datalabel = [1240, 190, 30, 545];
const myChart1 = new Chart("myChartline", {
type: 'line',
data: {
labels: labeltabmles,
datasets: [{
label: '# of Votes',
data: datalabel,
backgroundColor: "#007ee7",
borderColor: "#007ee7",
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
i want to configure the var labeltabmles = ['Redddd', 'Blue', 'Yellow', 'Green'];
var datalabel = [1240, 190, 30, 545]; using the variables listcount , listtype
where the result of this two array are following the code enter image description here
i need your help to pass listcount and listtype as paramter to datalabel and data of the chart
i tried but the apped didnt happen the this.listype and this.listcount still empty;
var labeltabmles = this.listcount ;
var datalabel = this.listype;
Thanks for your support and help
i find the solution by :
-using the TYPELIST: any = []; COUNTLIST: any = [];
-and update the variable used on push function on the for iteration
for (var key in data1) {
var typeelement = this.contentype[key]["type"];
var countelemtn = this.contentype[key]["count"];
this.TYPELIST.push(typeelement);
this.COUNTLIST.push(countelemtn);
}
const myChart1 = new Chart("myChartline", {
type: 'line',
data: {
labels: this.TYPELIST,
datasets: [{
label: '# of Votes',
data: this.COUNTLIST,
backgroundColor: "#007ee7",
borderColor: "#007ee7",
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});

Chart.js undefined variable in view

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
}
}]
}
}
});

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