ChartJS chart is bugged after adding new data - javascript

Actually in my website i build a char with some data from MySQL Database.
Every time the chart button is pressed a modal will appear an AJAX call will be sent to the server and then the Chart will be drawn.
The issue is that after adding new data to database and by opening the modal with the ChartJS by moving the mouse the ChartJS tilt between chart with new data and the old one.
Here is the code
var chart;
$(function () {
renderChart();
});
function renderChart() {
var ctx = document.getElementById('barchart').getContext('2d');
var gradient = ctx.createLinearGradient(0, 0, 0, 400);
gradient.addColorStop(0, '#007AFD');
gradient.addColorStop(1, '#00B1FF');
var options = {
legend: false,
maintainAspectRatio: false,
tooltips: {
displayColors: false
},
scales: {
xAxes: [{
gridLines: {
display: false,
},
barPercentage: 0.3,
}],
yAxes: [{
ticks: {
stacked: true,
stepSize: 1,
beginAtZero: true,
},
gridLines: {
borderDash: [5, 15],
drawBorder: false
}
}]
}
};
chart = new Chart(ctx, { type: 'bar', labels: [], data: [] });
}
function loadReports(data) {
$.ajax({
type: "POST",
url: "Default.aspx/getReports",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ data: data }),
dataType: "json",
success: function (r) {
data = r.d;
if (data != '[]') {
data = jQuery.parseJSON(data);
chart.data.labels = data.map(ora => ora.ORARIO);
chart.data.datasets[0].data[0] = data.map(cop => cop.COPERTI);
chart.update();
} else {
chart.data.labels = [];
chart.data.datasets[0].data = [];
chart.update();
}
},
error: function (error) {
alert(error.responseText);
}
});
}
buildChart() is called on load and chart is declared on top of JS file

Are you drawing a new chart by clicking on the button?
You should draw your chart just 1 time and then update the data:
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
}
function removeData(chart) {
chart.data.labels.pop();
chart.data.datasets.forEach((dataset) => {
dataset.data.pop();
});
chart.update();
}
Docs: https://www.chartjs.org/docs/latest/developers/updates.html
you can try it with this code:
$.ajax({
type: "POST",
url: "Default.aspx/getReports",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ data: data }),
dataType: "json",
success: function(r) {
data = r.d;
if (data != "[]") {
data = jQuery.parseJSON(data);
chart.data.labels = data.map(ora => ora.ORARIO);
chart.data.datasets[0].data = data.map(coperti => coperti.COPERTI);
chart.update();
} else {
chart.data.labels = [];
chart.data.datasets[0].data = [];
chart.update();
}
$("#modalChart").modal("show");
},
error: function(error) {
alert(error.responseText);
}
});

Related

How to input user data into chart from chart.js

I am using chart.js to display a graph of how much a user has in their account and of their expenses. I am using ajax to send that data to a php page. When I get a success response from ajax I want to update the chart after i close the modal which contains the form that sends data
Ajax:
$(document).ready(function () {
//use button click event
$("#pos_submit").click(function (e) {
e.preventDefault();
let pos_amount = $("#pos_amount").val();
let pos_category = $("#pos_category").val();
let pos_date = $("#pos_date").val();
$.ajax({
method: "post",
url: "add-positive-value.php",
data: {
pos_amount: pos_amount,
pos_category: pos_category,
pos_date: pos_date
},
success: function (response) {
console.log(response);
if (response === "success") {
$("#pos_response").html("<div class='alert alert-success' role='alert'>Successfully added an amount of $" + pos_amount + "</div>");
$.ajax({
type: "GET",
url: "get_budget.php",
success: function (response) {
$("#enroll").on("hidden.bs.modal",function () {
$("#full_budget").html("<p>$" + response + "</p>");
addData(my_chart,response);
});
}
})
}else {
$("#pos_response").html(response);
}
},
error: function (response) {
alert(JSON.stringify(response));
}
})
})
});
Chart.js code:
let my_chart = document.getElementById("myChart").getContext('2d');
//Global options
Chart.defaults.global = {
FontFamily:"Lato",
defaultFontSize:18,
defaultFontColor: "#00ff00"
}
let massPopChart = new Chart(my_chart,{
type: 'pie', //bar, horizontal bar, pie, line ,doughnut, radar, polar area
data:{
labels:['Budget', 'Expenses'],
datasets:[{
// label: 'Budget',
data:[
<?php echo $budget; ?>,
<?php echo $expenses; ?>
],
backgroundColor:[
'green',
'red'
],
borderWidth: 1,
hoverBorderWidth:3,
hoverBorderColor:'black'
}]
},
options:{
plugins:{
title:{
display:true,
text:'Your balance',
font:{
size:30
}
},
legend:{
position:'bottom',
labels:{
fontColor: "black",
font:{
size: 20
}
}
},
layout:{
padding:{
left:0,
right:0,
bottom:0,
top:0
}
},
}
}
});
function addData(chart, data) {
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
}
However I don't know how to do that

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) {
//
}
});
});

Make chartjs pie chart wiyh dynamic data

I can't display my ChartJS pie chart with dynamic data, I googled a lot and I couldn't find a solution, so I'm here for your help.
window.onload = function() {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/1',
dataType: "json",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data) {
// var dataResults = data.d.results;
var tempData = [{
EnterpriseProjectTypeName: 'first project'
},
{
EnterpriseProjectTypeName: 'first project'
},
{
EnterpriseProjectTypeName: 'first project'
},
{
EnterpriseProjectTypeName: 'second project'
},
{
EnterpriseProjectTypeName: 'third project'
},
{
EnterpriseProjectTypeName: 'test'
}
];
var itermeidiaryObject = {};
$.each(tempData, function(key, value) {
var epn = value.EnterpriseProjectTypeName;
var som = 0;
if (epn != null) {
itermeidiaryObject[epn] = ++itermeidiaryObject[epn] || 1;
}
var somme = som;
});
var finalObject = Object.keys(itermeidiaryObject).map(function(key) {
return {
label: key,
y: itermeidiaryObject[key]
}
});
var ctx = document.getElementById('myChart').getContext('2d');
var lables=tempData
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: finalObject,
datasets: [{
data: finalObject,
}]
},
options: {
responsive: false,
scales: {
xAxes: [{
ticks: {
maxRotation: 90,
minRotation: 80
}
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
});
}
And this is the html part
<canvas id="myChart"></canvas>
</div><script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
Can any one help me please?
Do you want a pie chart or a bar chart ? Edited things a little so that it makes a pie chart, although you can just go back to the bar chart with a few edits regarding mostly the way labels were handled since it looks like they need to be single values in an array. Probably a better way, but this should help. This is for the pie chart. You had a rogue div in the HTML also.
window.onload = function() {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/1',
dataType: "json",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function(data) {
// var dataResults = data.d.results;
var tempData = [{
EnterpriseProjectTypeName: 'first project'
},
{
EnterpriseProjectTypeName: 'first project'
},
{
EnterpriseProjectTypeName: 'first project'
},
{
EnterpriseProjectTypeName: 'second project'
},
{
EnterpriseProjectTypeName: 'third project'
},
{
EnterpriseProjectTypeName: 'test'
}
];
var itermeidiaryObject = {};
$.each(tempData, function(key, value) {
var epn = value.EnterpriseProjectTypeName;
var som = 0;
if (epn != null) {
itermeidiaryObject[epn] = ++itermeidiaryObject[epn] || 1;
}
var somme = som;
});
var finalObject = Object.keys(itermeidiaryObject).map(function(key) {
return {
label: key,
y: itermeidiaryObject[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);
console.log(labels);
console.log(pievalues);
console.log(finalObject);
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: labels,
datasets: [{
data: pievalues,
backgroundColor: colorscheme
}]
},
options: {
responsive: false,
}
});
}
});
}
var colors = ["#0074D9", "#FF4136", "#2ECC40", "#FF851B", "#7FDBFF", "#B10DC9", "#FFDC00", "#001f3f", "#39CCCC", "#01FF70", "#85144b", "#F012BE", "#3D9970", "#111111", "#AAAAAA"];
<canvas id="myChart"></canvas>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
I am presuming that the data you provided in the handler success is pretty much what you get back as JSON ?

Redraw JQplot bar chart with new data and tick labels

My code successfully draws a chart with data and tick labels retrieved as JSON object from PHP. Now at one point i want to refresh the chart but with slightly different data and different tick labels without creating a new chart.
$.jqplot.config.enablePlugins = true;
var freqs1 = [];
var freqlabels1 = [];
var dataRendered1 = $.ajax({
async: false,
url: 'MY_URL',
dataType: 'json',
success: function(data) {
if (data.length) {
freqs1 = data[0];
freqlabels1 = data[1];
}
}
});
var plot1 = $.jqplot('chartdiv', [freqs1], {
animate: !$.jqplot.use_excanvas,
seriesDefaults:{
renderer:$.jqplot.BarRenderer,
pointLabels: {
show: true
},
rendererOptions: {
barWidth: 12
}
},
title:'Test',
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: freqlabels1,
label: "Test 1",
tickOptions:{textColor : 'rgb(39, 125, 175)', fontSize: '9pt'}
},
yaxis: {
label: "Test 2",
labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
tickOptions:{textColor : 'rgb(39, 125, 175)', fontSize: '9pt'}
}
},
highlighter: { show: true }
});
now when button is clicked lets say I have an ajax call that gets the new data and tick labels
$(document).on('click', '#refresh_new', function() {
$.ajax({
async: false,
url: 'MY_URL',
dataType: 'json',
success: function(data) {
var newData = data[0];
var newTicks = data[1];
//HOW DO I REFRESH CHART WITH NEW DATA AND TICKS FOR x-AXIS
}
});
});

highcharts dynamically adding series with addSeries

I'm working on creating a dynamically created chart that will add a series if there isn't one and if there is one add a point. I'm getting an Uncaught TypeError: Cannot call method 'addSeries' of undefined. I've looked around and I can't find why it says that method is undefined.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="highcharts.js"></script>
$(document).ready(function () {
var chart1 = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column',
events: {
load: requestData
}
},
title: {
text: 'Survey Chart'
},
xAxis: {
categories: [],
title: {
text: 'Question Number'
}
},
yAxis: {
title: {
text: 'Total Answered'
}
},
legend: {
layout: 'vertical',
align: 'left',
verticalAlign: 'top',
x: 100,
y: 70,
floating: true
},
series: []
});
with the document ready function taking up the entire script i have the following functions
function requestData() {
ajaxCall(chartCreate, createSeries, "services/Survey.svc/DoWork", "{}");
chart1.redraw();
};
function chartCreate(point) {
var temp;
temp = $.parseJSON(point.d);
$.each(temp, function (key, p) {
var seriesObj;
seriesObj = seriesExists(p.mcAnswer);
if (seriesObj.status == false) {
chart1.addSeries({name: '' + p.mcAnswer + '', data: [] });
chart1.series[seriesObj.count].addPoint(p.total, false);
} else {
chart1.series[seriesObj.count].addPoint(p.total, false);
}
});
};
//loops through all the series to see if the series exists.
//if true returns index and true if not just returns false
function seriesExists(name) {
var ct = 0;
//var len = chart1.series.length;
var len = 0;
if (len > 0) {
$.each(chart1.series, function (count, curSeries) {
if (curSeries.name == name) {
return { 'count': count, 'status': true };
}
ct = count;
});
}
return { 'count': ct, 'status': false };
}; function createSeries() {
alert("error");
};
//$.ajaxCall({successFun: function, errorFun: function, source: "", data: {}});
function ajaxCall(myFunSuccess, myFunError, url, data) {
//chart1 = chartTemp;
$.ajax({
type: "POST",
async: false,
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: myFunSuccess,
error: myFunError
});
//return chart1;
};
I'm able to use the ajax function call fine it's when I get to my chartCreate where I run into the problem.
The problem is that you're trying to add the serie before chart1 get your chart reference. That's why chart1 doens't have addSeries method.
You can see this issue here.
To fix it you can set manually the chart reference to chart1 before call requestData.
Like the following.
load: function() {
chart1 = this; // `this` is the reference to the chart
requestData();
}

Categories

Resources