Redraw JQplot bar chart with new data and tick labels - javascript

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

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

ChartJS chart is bugged after adding new data

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

Highcharts load data from server ok, but not updating

I load succesfully from database but then it doesn't update dynamic. The function InitHighchart produce Highchart and I am trying to update series using requestData function
function requestData() {
$.ajax({
url: 'http://....url.../json.php',
data: {region:region},
type: 'post',
dataType: 'json',
error: function (point) {
var series = chart.series[0],
shift = series.data.length > 50; // shift if the series is longer than 20
var values = eval(point);
chart.series[0].addPoint([values[0], values[1]], true, shift);
chart.series[1].addPoint([values[0], values[2]], true, shift);
// call it again after defined seconds
setTimeout(requestData, 1000);
},
success: function (point) {
var series = chart.series[1],
shift = series.data.length > 50; // shift if the series is longer than 20
// add the point
// chart.series[0].addPoint(eval(point), true, shift);
var values = eval(point);
chart.series[0].addPoint([values[0], values[1]], true, shift);
chart.series[1].addPoint([values[0], values[2]], true, shift);
// call it again after defined seconds
setTimeout(requestData, 1000);
},
cache: false
});
}
and here the chart
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script>
//is it right here to define chart?
var chart; // global
var region = "<?php Print($region); ?>";
function requestData() {
$.ajax({
url: 'http://cstation.admie.gr/iREACT_cSTATION_WEB/trexousa_katastasi/json.php',
data: {region:region},
type: 'post',
dataType: "json",
error: function (point) {
var series = chart.series[0],
shift = series.data.length > 50; // shift if the series is longer than 20
var values = eval(point);
chart.series[0].addPoint([values[0], values[1]], true, shift);
chart.series[1].addPoint([values[0], values[2]], true, shift);
// call it again after defined seconds
setTimeout(requestData, 1000);
},
success: function (point) {
var series = chart.series[1],
shift = series.data.length > 50; // shift if the series is longer than 20
// add the point
// chart.series[0].addPoint(eval(point), true, shift);
var values = eval(point);
chart.series[0].addPoint([values[0], values[1]], true, shift);
chart.series[1].addPoint([values[0], values[2]], true, shift);
// call it again after defined seconds
setTimeout(requestData, 1000);
},
cache: false
});
}
function InitHighChart()
{
$("#chart1").html('LOADING');
var options =
{
chart: {
renderTo: 'chart1',
borderColor: '#a1a1a1',
borderRadius: 13,
alignTicks: false,
zoomType: 'xy',
height: 700,
events : {
load :requestData()
}
},
credits: {
enabled: false
},
title: {
text: "",
x: -50
},
xAxis: {
series: [{}],
labels: {
rotation: -75
}
},
yAxis: [{ //Primary yAxis
labels: {
format: '{value}',
style: {
color: "#000000"
}
},
title: {
text: '',
style: {
color: "#0B0EED"
}
}
}
],
tooltip: {
formatter: function() {
var s = '<b>'+ this.x +'</b>';
$.each(this.points, function(i, point)
{
s += '<br/>'+point.series.name+': '+point.y;
});
return s;
},
shared: true
},
series: [{},{}]
};
//ajax call
$.ajax({
url: "http://...url.../json1.php",
data: {region:region},
type:'post',
dataType: "json",
success: function(data)
{
options.xAxis.categories = data.datetime;
options.series[0].name = 'Συνολικό Φορτίο (MWatt)';
options.series[0].data = data.SD_PData;
options.series[0].color = "#05A43C";
options.series[1].name = 'Συνολικό Φορτίο Φαινομένου (MVar)';
options.series[1].data = data.SD_MVAData;
options.series[1].color = "#EC2E03";
var chart = new Highcharts.Chart(options);
},
});
}
</script>
<!-- 3. Add the container -->
<div id="chart1" style="width: 1200px; height: 700px; margin: 0 auto"><body onload="InitHighChart()"></div>
Try this out. I have done the same thing in one of my code.
var options = {
chart: {
renderTo: 'chart',
defaultSeriesType: 'column'
},
title: {
text: 'Voting Results'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'votes'
}
},
series: [{}]
};
$.getJSON('votecount2.php', function(data) {
options.series[0].name = "Votes";
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
My JSON is this
[["Waseem Akhtar",5],["Imran Ismail",4],["Qaim Ali Shah",4]]

csv live data highchart

My data won't display proper.
I have this kind of data: "1456135353.000000|5424492576222277|8156610153681827"
"1456135353" is for the time.
"5424492576222277" is for the first X
"8156610153681827" is for the second X
This is my code:
var chart
/**
* Request data from the server, add it to the graph and set a timeout
* to request again
*/
function requestData () {
$.ajax({
url: 'api/chart',
dataType: 'text',
success: function (point) {
var series = chart.series[0].push
// longer than 20
// add the point
chart.series[0].addPoint(point, true)
// call it again after one second
setTimeout(requestData, 1000)
},
cache: false
})
}
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'line',
events: {
load: requestData
}
},
title: {
text: 'XSnews Graph'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
gridLineColor: '#197F07',
gridLineWidth: 1,
title: {
text: 'GB',
margin: 80
}
},
series: [{
name: 'Time',
data: []
}]
})
})
I am not familiar with Highcharts so I have no clue what I am doing wrong.
Do I need to parse it?
You need to parse your data first, before adding a point. Something like this:
success: function (point) {
var options = point.split("|"),
x = parseFloat(options[0]) * 1000,
y_1 = parseFloat(options[1]),
y_2 = parseFloat(options[2]);
chart.series[0].addPoint([x, y_1], true);
setTimeout(requestData, 1000)'
}

HighCharts : Tooltips exist but line is not drawn in the chart

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

Categories

Resources