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
Related
I am trying to poll my data in HighCharts. The graph in this link is what I am trying to achieve. I am using Ajax request to retrieve my data. Here is my code:
setInterval(RefreshGraph, 3000);
...
...
function RefreshGraph() {
var options = {
chart: {
type: 'spline'
},
title: {
text: 'Text'
},
xAxis: {
title: {
text: 'TIMEFRAME'
},
categories: ['-4m', '-3m', '-2m', '-1m', 'Now']
},
yAxis: {
title: {
text: 'NUMBER'
},
},
tooltip: {
crosshairs: true,
shared: true
},
plotOptions: {
spline: {
marker: {
radius: 4,
lineColor: '#666666',
lineWidth: 2
}
}
},
series: [{}]
};
Highcharts.ajax({
url: "/Home/GetData",
success: function (data) {
var formattedData = FormatData(data);
//Graph 1
options.series[0] = formattedData[0];
//Graph 2
options.series[1] = formattedData[1];
Highcharts.chart("container", options);
}
});
}
However, the entire graph gets redrawn with my above code. How can I enable live polling for the above code?
You create a chart every time data is received. You need to create a chart and then update it. Example:
const options = {...};
const chart = Highcharts.chart("container", options);
function RefreshGraph() {
Highcharts.ajax({
url: "/Home/GetData",
success: function(data) {
var formattedData = FormatData(data);
chart.update({
series: [formattedData[0], formattedData[1]]
});
}
});
}
setInterval(RefreshGraph, 3000);
Live demo: http://jsfiddle.net/BlackLabel/6d5stjab/
API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#update
I am trying to create a Google area chart in model using AJAX. If I use the response from the AJAX request then the Google Chart doesn't work. If I use default values, then it works. Where is the problem? Thanks in advance.
function showDetails(REPORTNO, date1, date2, locid, cancelId) {
$.ajax({
url: "catdetail.php",
method: "POST",
async: true,
data: {
"REPORTNO": REPORTNO,
"date1": date1,
"date2": date2,
"locid": locid,
"cancelId": cancelId
},
success: function(response) {
var qty = "";
details = JSON.parse(response);
$.each(details, function(i) {
res = details[i];
timeord = res[0];
catqty = res[1];
qty += "['" + timeord + "'," + catqty + "],";
})
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
alert(qty);
var data = google.visualization.arrayToDataTable([
['Time', 'Qty'],
//['1', 12],['2', 12],['3', 12],['4', 12],['5', 12]
qty
]);
var options = {
title: 'Company Performance',
hAxis: {
title: 'Category Sales by Time',
titleTextStyle: {
color: '#333'
}
},
vAxis: {
minValue: 0
},
pointSize: 18,
pointShape: {
type: 'star',
sides: 5,
dent: 0.5
}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_detail'));
chart.draw(data, options);
}
}
});
};
<div id="chart_detail" style="width: 100%; height: 500px"></div>
since you're sending an array in json format,
you do not need to rebuild the array on the client.
you only need to add the column headings. (which could probably be done in php as well)
success: function(response) {
var details = JSON.parse(response);
details.ushift(['Time', 'Qty']);
then use details to create the data table.
var data = google.visualization.arrayToDataTable(details);
see following snippet...
function showDetails(REPORTNO, date1, date2, locid, cancelId) {
$.ajax({
url: "catdetail.php",
method: "POST",
async: true,
data: {
"REPORTNO": REPORTNO,
"date1": date1,
"date2": date2,
"locid": locid,
"cancelId": cancelId
},
success: function(response) {
var details = JSON.parse(response);
details.ushift(['Time', 'Qty']);
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable(details);
var options = {
title: 'Company Performance',
hAxis: {
title: 'Category Sales by Time',
titleTextStyle: {
color: '#333'
}
},
vAxis: {
minValue: 0
},
pointSize: 18,
pointShape: {
type: 'star',
sides: 5,
dent: 0.5
}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_detail'));
chart.draw(data, options);
});
}
});
};
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);
}
});
I met with a problem on HighCharts.
I had to gather data from a xml content with ajax in order to draw it in a HighCharts chart.
I get my datas. I can see my points when I move my mouse over it but my chart is not displaying anything.
A picture to see the problem :
mouse over the third point
And some parts from my code if it can help :
var myData=[];
function makeChart() {
var chart;
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container2',
type: 'spline',
borderColor: '#DC143C',
borderRadius: 20,
borderWidth: 2,
marginRight: 130,
marginBottom: 25
},
title: {
text: ''
},
xAxis: {
categories :[0,1,2,3,4,5]
},
yAxis: {
title: {
text: 'Values'
},
},
series: [{
color: '#FF00FF',
name: '',
data: myData
}]
});
});
}
$(function (){
$(document).ready(function ping(){
ChartDeOuf();
makeChart();
$.ajax({
type: "GET",
url: 'http://localhost:8080/SASI/runSimulation',
dataType: "xml",
success: function(result){
var i = 0;
var xmlDoc = $.parseXML(result);
var chart = $('#container2').highcharts();
$result = $(xmlDoc);
$(result).find('measure').each(function(){
var $value = $(this);
var attr = $value.attr("meanValue");
myData[i]=attr;
var html = '<p> '+myData[i]+'</p>';
chart.series[0].addPoint({y: myData[i]},false);
chart.redraw();
$('body').append($(html));
i++;
})
},
error: function(result){
alert('timeout/error');
}
});
});
});
Thanks for reading.
Got it, that line saved everything :
myData[i]=parseFloat(attr);
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
}
});
});