How to update Chart.js based on dropdown list? - php

UPDATED
I have added a dropdown to my chart which allows the user to select among the available operator names.
I need your help so that when selecting an available operator name, the graphic is updated showing only the information of the selected operator.
From all my JSON response, for this example it should only show the information in a red box:
As you can see in the image, if I select the Luis operator, this graph should update and show me only the Luis operator (he has 2 work orders in finished state).
Below my report.js file which I use to make the graph.
getChartData () method:
I use ajax, basically I'm getting the data and loading my select with the names of the available operators.
renderChart () method:
 
I am passing it as a parameter "label and data" with these parameters I can make my graph also I am configuring some available options.
select.on ('change', function ():
here I do not understand how to tell my chart to update depending on the option selected, then I would have to call the renderChart method again to graph again with the selected data but it does not work, I do not know how to solve it, it is what I am trying.
report.js
function getChartData(user) {
$.ajax({
url: '/admin/reports/getChart/' + user,
type: 'GET',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
dataType: 'json',
success: function (response) {
console.log(response);
var data = [];
var labels = [];
for (var i in response.orders) {
data.push(response.orders[i].orders_by_user);
labels.push(response.orders[i].name);
$("#operator").append('<option value='+response.orders[i].id+'>'+response.orders[i].name+'</option>');
}
renderChart(data, labels);
},
error: function (response) {
console.log(response);
}
});
}
function renderChart(data, labels) {
var ctx = document.getElementById("orders").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Terminadas',
data: data,
borderColor: 'rgba(75, 192, 192, 1)',
backgroundColor: "#229954",
borderWidth: 1,
yAxisID: 'Ordenes',
xAxisID: 'Operarios',
}]
},
options: {
scales: {
yAxes: [{
id: "Ordenes",
ticks: {
beginAtZero: true
},
scaleLabel: {
display: true,
labelString: 'Ordenes'
}
}],
xAxes: [{
id: "Operarios",
scaleLabel: {
display: true,
labelString: 'Operarios'
}
}],
},
title: {
display: true,
text: "Ordenes en estado terminado"
},
legend: {
display: true,
position: 'bottom',
labels: {
fontColor: "#17202A",
}
},
}
});
function updateChart() {
myChart.destroy();
myChart = new Chart(ctx, {
type: document.getElementById("operator").value,
data: data
});
};
}
getChartData();
$('#operator').select2({
placeholder: 'Selecciona un operario',
tags: false
});
var select = $('#operator');
var pElem = document.getElementById('p')
select.on('change', function() {
var item = $(this).val();
pElem.innerHTML = 'selectedValue: ' + item;
var data = {
labels: labels,
datasets: data
}
var ctx = document.getElementById("orders").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: data
});
});
My select:
<select class="form-control" name="operator" id="operator">
<option></option>
</select>
I get lost trying to link the selected option and the information to show (update the graph). Could you please tell me how to solve this?
UPDATED 1
My select:
<select class="form-control" name="operator" id="operator">
<option></option>
</select>
Through ajax I load my select options:
for (var i in response.orders) {
order.push(response.orders[i].orders_by_user);
user.push(response.orders[i].name);
$("#operator").append('<option value='+response.orders[i].id+'>'+response.orders[i].name+'</option>');
}
renderChart(order, user);
With the answer you have given me, modify my report.js file exactly my function renderChart(order, user) and it is as follows:
function renderChart(order, user) {
var ctx = document.getElementById("orders").getContext('2d');
var myChart = new Chart(ctx, {
//code...
});
//my select
var selectOption = $('#operator');
selectOption.on('change', function() {
var option = $("#operator").val();
myChart.data.labels = option;
if (option == 'All') {
myChart.data.labels = user,
myChart.data.datasets[0].data = order;
} else {
myChart.data.labels = option;
myChart.data.datasets[0].data = order;
}
myChart.update();
});
}
The graph is updated incorrectly an error occurs you can see it in the image:
Obviously if I select the "All" option, it shows and graphs correctly, now if I select "jose" the following happens:
The graph does not respect the scale, I know that Jose has only 1 work order, and up to 2 on the scale.
On the x axis instead of showing me the name in this case "Jose" is showing me the selection id which in this case is 6.
The same happens with the option "Miguel".
Please help me correct this section:
var selectOption = $('#operator');
selectOption.on('change', function() {
var option = $("#operator").val();
myChart.data.labels = option;
if (option == 'All') {
myChart.data.labels = user,
myChart.data.datasets[0].data = order;
} else {
myChart.data.labels = option;
myChart.data.datasets[0].data = order;
}
myChart.update();
});

When the selected options changes, you must not destroy the chart. All you need to do is performing the following steps.
Change the data.labels
Change the data of the unique dataset
Update the chart itself
This is basically done as follows.
myChart.data.labels = <new labels>;
myChart.data.datasets[0].data = <new values>;
myChart.update();
The following example illustrates how this can be done in JavaScript.
orders = [
{ name: 'Luis', orders_by_user: '2' },
{ name: 'Jose', orders_by_user: '1' },
{ name: 'Miguel', orders_by_user: '3' }
];
const myChart = new Chart(document.getElementById('orders'), {
type: 'bar',
data: {
labels: orders.map(o => o.name),
datasets: [{
label: 'Terminadas',
data: orders.map(o => o.orders_by_user),
borderColor: 'rgba(75, 192, 192, 1)',
backgroundColor: "#229954",
borderWidth: 1,
yAxisID: 'Ordenes',
xAxisID: 'Operarios',
}]
},
options: {
scales: {
yAxes: [{
id: "Ordenes",
ticks: {
beginAtZero: true,
stepSize: 1
},
scaleLabel: {
display: true,
labelString: 'Ordenes'
}
}],
xAxes: [{
id: "Operarios",
scaleLabel: {
display: true,
labelString: 'Operarios'
}
}],
},
title: {
display: true,
text: "Ordenes en estado terminado"
},
legend: {
display: true,
position: 'bottom',
labels: {
fontColor: "#17202A",
}
},
}
});
orders.forEach(o => {
const opt = document.createElement('option');
opt.value = o.name;
opt.appendChild(document.createTextNode(o.name));
document.getElementById('operator').appendChild(opt);
});
function refreshChart(name) {
myChart.data.labels = [name];
if (name == 'All') {
myChart.data.labels = orders.map(o => o.name),
myChart.data.datasets[0].data = orders.map(o => o.orders_by_user);
} else {
myChart.data.labels = [name];
myChart.data.datasets[0].data = orders.find(o => o.name == name).orders_by_user;
}
myChart.update();
}
Operarios:
<select id="operator" onchange="refreshChart(this.value)">
<option>All</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="orders" height="90"></canvas>

Related

How to show multiple highcharts on selection of few parameters and dynamically load JSON data using PHP page?

I have two parameters to load dynamic json data from mysql and visualise multiple line charts on page submit.
$.ajax({
url: 'get_pubmedid.php',
type: 'get',
data: {org: org, ptype: ptype, path: path,mirna: mirna},
dataType: 'json',
success:function(response) {
var len = response.length;
for( var i = 0; i<len; i++) {
pubmed = response[i]['name'];
cell=response[i]['cell'];
alert(cell+" "+pubmed+" "+len);
var cells=encodeURIComponent(cell);
var cname="charts"+(i+1);id=i+1;var pid=i+1;
var container = cname;
var func_name = cname;
func_name = function () {
Highcharts.chart(container, {
showhighcharts(org,ptype,path,mirna,cell,cells,pid,pubmed,cname,id);
}
}
func_name()
}
}
});
function showhighcharts(org,ptype,path,mirna,cell,cells,pid,pubmed,cname,id) {
$("#"+cname).html("Wait, Loading graph...");
var options = {
chart: {
type: 'line',
renderTo: cname
},
colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'],
credits: {
enabled: false
},
title: {
text: 'Temporal Viewer',
x: -20
},
xAxis: {categories:<?php //echo $_SESSION["cat"]; ?>,
offset:2,
title: {enabled: true,text: 'Time Point' }
},
tooltip: {
shared: true,
useHTML: true,
headerFormat: '<b>Time Point:{point.key}</b> <table style="width:200px;font-size:12px;font-weight:bold;">',
pointFormat: '<tr><td>Dosage:</td><td style="color: {series.color}">{series.name} </td></tr>' + '<tr><td>Fold Change:</td><td style="color: {series.color}">{point.y} </td></tr>',
footerFormat: '</table>',
enabled: true,
crosshairs: {
color: 'light gray',
dashStyle: 'longdash'
}
},
plotOptions: {
series: {
dashStyle: 'longdash'
},
line: {
dataLabels: {
enabled: true
},
enableMouseTracking: true
}
},
series: [{}]
};
$.ajax({
url: "jdatas.php?org="+org+"&ptype="+ptype+"&path="+path+"&mirna="+mirna+"&pid="+id+"&cell="+cell+"&pub="+pubmed,
data: 'show=impressions',
type:'get',
dataType: "json",
success: function(data){
var getSeries = data;
options.series = getSeries;
var chart1 = new Highcharts.Chart(options);
}
});
I want multiple graphs to be loaded on submit.
But its not showing any graph.

how can I modify my function via ajax?

well, to start I used to make my JSON function, but when I wanted add data I couldn't. So How can I my json function ? i'm using getJSON but I can't add data like ajax then how could I change it to ajax style. it's for hightchart
$(function() {
var processed_json = new Array();
$.getJSON('../controllers/chart_controller.php', function(data){
for (i = 0; i < data.length; i++){
processed_json.push([data[i].key,data[i].value]);
}
//draw chart
$('#salesChart').highcharts({
chart: {
type: "column"
},
title: {
text: "Best selling product"
},
xAxis: {
type: 'category',
allowDecimals: false,
title: {
text: ""
}
},
yAxis: {
title: {
text: "Scores"
}
},
series: [{
name: 'Sales',
data: processed_json
}]
});
});
});

highchart Dynamically updated data

i want to set up highcharts.
i made a simple random number in this url
http://echocephe.com/new/custom_number.php
i want to use these random datas on Dynamically updated data charts
this is code can you help me to solve this problem thanks.
<script type="text/javascript">
$(function () {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
})()
}]
});
});
});
</script>
maybe its better to check highchart forums
here is the answer
http://www.highcharts.com/docs/working-with-data/preprocessing-live-data/

Highcharts Pie Chart from Ajax

I have a page that uses highcharts pie chart, and I am trying to update the chart with a date selector drop down. I have a similar implementation for a bar chart and its working great. Please note (this is coming from a PHP class, hence the concatenation and what not).
<script type='text/javascript'>
function drawPie(data)
{
var chart;
alert('called');
var options = {
chart: {
renderTo: 'PieChart',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
height: 350
},
title: {
text: 'Product Popularity'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {enabled: false},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'Product Popularity',
data: data
}]
}
chart = new Highcharts.Chart(options);
$('#ProductPieMod div.mod_content').css('height', $('#PieChart').css('height'));
}
$(document).ready(function(){
drawPie(" . $this->get_data($this->date) . ");
$('#ProductPieMod_date').on('change', function(){
var val = parseInt($(this).val());
switch(val)
{
case 0:
var date = Date.today();
break;
case 1:
var date = Date.parse('last week');
break;
case 2:
var date = Date.today().moveToFirstDayOfMonth();
break;
case 3:
var date = Date.parse('January').moveToFirstDayOfMonth();
break;
default:
var date = Date.today();
}
var info;
$.ajax({
type: 'POST',
url: '". matry::base_to('utilities/dhs/manager_dash') . "',
async: false,
dataType: 'json',
data: {date: date.toString('M/dd/yyyy'), module: 'ProductPieMod'},
success: function(data)
{
drawPie(data);
}
});
});
});
</script>
My ajax returns the following string:
[['FASTCLIX LANCING DEVICE', 62.5],['FREESTYLE LANCING DEVICE', 25],['ONETOUCH DELICA LANCING DEVICE', 12.5]]
In addition, this chart is initially built, using the exact same method, just fine. Its just when I use the dropdown (run the onChange event) that it breaks.
Update
I have created a fiddle for this as well: http://jsfiddle.net/SHReZ/1/
Firts, you need to place chart var to document.ready handler scope, next, you need to destroy chart before draw.
$(document).ready(function () {
var chart;
function drawPie(data) {
console.log('called');
var options = {
chart: {
renderTo: 'PieChart',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
height: 350
},
title: {
text: 'Product Popularity'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
}
},
series: [{
type: 'pie',
name: 'Product Popularity',
data: data
}]
};
if (chart !== undefined) chart.destroy();
chart = new Highcharts.Chart(options);
$('#ProductPieMod div.mod_content').css('height', $('#PieChart').css('height'));
}
drawPie([
['ONETOUCH DELICA LANCING DEVICE', 27.78],
['FREESTYLE LANCING DEVICE', 20.83],
['Nova Max Ketone Test Strips Health and', 11.11],
['ONETOUCH ULTRASOFT LANCING DEVICE 2PK', 11.11]
]);
//get data from https://gist.github.com/zba/4712055 , delay 4
$.post('/gh/gist/response.html/4712055', {
delay: 4
}, function (data) {
drawPie(data);
}, 'json');
});
fiddle
also here is demo which not destroy chart, but it change colors to much

Kendo Grid. How to display dataTextField in Grid's cell instead of dataValueField?

I want to display Text for my ForigenKey columns instead of numeric values. There are a lot of examples to retrieve TextMember by comparing ID but they are not working in my case. I just started to use Kendo ui so dont know much about it
Here is the code :
$(document).ready(function () {
dataSource1 = new kendo.data.DataSource({
transport: {
read: {
url: "Data/AttendanceCode/GridSelect.php",
dataType: "json",
},
update: {
url: "Data/AttendanceCode/GridUpdate.php",
dataType: "json",
type:"GET"
},
destroy: {
url: "Data/AttendanceCode/GridDelete.php",
dataType: "json",
type:"POST"
},
create: {
url: "Data/AttendanceCode/GridInsert.php",
dataType: "json",
type:"POST"
},
},
schema: {
data: "data",
model: {
id: "AttendenceID",
fields: {
AttendenceID : { editable: false, nullable: true },
TeacherID: { field: "TeacherID", defaultValue: "EIIT0002" },
}
}
},
});
$("#grid").kendoGrid({
dataSource: dataSource1,
pageSize: 10,
pageable: {
refresh: true,
pageSizes: true
},
editable:{ mode : "popup" },
height: 400,
filterable: true,
columnMenu: true,
sortable: true,
reorderable: true,
resizable: true,
toolbar: ["create"],
columns: [
{ field:"AttendenceID", title: "Attendence ID", width:"130px" },
{ field: "TeacherID", title:"Teacher", width: "100px" , editor: TeacherDropDownEditor, template: "#=getTeacherName(TeacherID)#" },
{ command: ["edit", "destroy"], title: "Action", width: "210px" }],
});
});
Teacher DropDown DataSource
teacher = new kendo.data.DataSource({
transport: {
read: {
url : "Data/Teacher.php",
dataType: "json" }
},
schema: {
data : "Teacher"
}
});
// Teacher Editor
function TeacherDropDownEditor(container, options) {
$('<input data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
dataTextField: "TeacherName",
dataValueField: "Service_NO",
dataSource: teacher
});
}
Different approaches i found and tried to Get Teacher Name
1 -
function getTeacherName(value) {
var text = "";
$.each(teacher, function () {
if (this.Service_NO == value) {
text = this.Name;
return false;
}
});
return text;
}
2 -
function getTeacherName(teacherID) {
for (var idx = 0, length = teacher.length; idx < length; idx++)
{
if (teacher[idx].Service_NO === teacherID)
{t = teacher[idx].Name;}
}
return t;
}
3 -
function getTeacherName(teacherID) {
$.each(teacher, function(key, val) {
if(val.Service_NO == tID){
t = val.Name;
}
});
return t;
}
It seems like dataSource (teacher) is not having any value.
PHP code is working perfectly.
Please Help if you have any idea whats wrong with my code.
Thanks !!
You are right, teacher DataSource does not have any data because you are defining how to get the data (that's what you do with the DataSource) but you are not reading it.
Add:
teacher.read();
for manually forcing the data read.
NOTE: This is something that happens magically when you have a Grid, ListView,... because these widget do it for you but this time, for displaying your grid you need to read it in advance since it is invoked from a JavaScript function (KendoUI grid code doesn't know anything about what you have in the function getTeacherName other than the name).
you should config your field:
{ field: "nu_status", title: 'Status', values: [ { text: "Active", value: 1 }, { text: "Inactive", value: 0 }]},

Categories