Updating jqplot Pie Chart via JS not working - javascript

I am trying to update jqplot PieChart via JS since yesterday and I am not having any breakthrough with this. I have searched online and cant seem to get any solution work
The chart data is saved in session and this session is continuously being updated by the application.
This is what the JSON looks like
[ ['Take home pay', 44228.33], ['Tax', 8771.67], ['Super', 4162.5 ], ['Regular expenses', 0 ], ['Unallocated', 44228.33], ['Testing', 8000] ]
The chart loads fine when the user navigates to the page for the first time.
This is the DIV where the chart loads
<div id="savings_expense" class="jqplot-target"></div>
This is the jqplot JS when the page loads which works fine
$(document).ready(function () {
var storedData = <?php echo $_SESSION['chart_data'] ?>;
var plot1;
jQuery.jqplot.config.enablePlugins = false;
plot1 = jQuery.jqplot('savings_expense', [storedData],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: {
show: true,
rendererOptions: {
numberRows: 6
},
placement: 'outside',
location: 's',
marginTop: '15px'
}
}
);
});
This is the button that user clicks to update the chart.
<li onclick="updateGraph()">YOUR TAKE-HOME PAY</li>
I have tried two ways to update the PieChart
Solution 1
In this solution I get the error Uncaught TypeError: Cannot read property 'replot' of undefined.
var storedData = <?php echo $_SESSION['chart_data'] ?>;
var plot1;
function renderGraph() {
plot1.replot({
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: {
show: true,
rendererOptions: {
numberRows: 6
},
placement: 'outside',
location: 's',
marginTop: '15px'
}
});
}
function updateGraph() {
alert('updateGraph');
var newVal = <?php echo $_SESSION['chart_data'] ?>;
storedData.push(newVal);
renderGraph();
}
Solution 2
In this solution the pie chart goes blank but the legends stay
var storedData = <?php echo $_SESSION['SMP']['chart_data'] ?>;
var plot1;
function renderGraph() {
if ( plot1) {
plot1.destroy();
}
jQuery.jqplot.config.enablePlugins = false;
plot1 = jQuery.jqplot('savings_expense',[storedData],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: {
show: true,
rendererOptions: {
numberRows: 6
},
placement: 'outside',
location: 's',
marginTop: '15px'
}
}
);
}
I will really appreciate any help here. Please do not share any links as I have gone through about every solution I could find on StackOverflow and on net

You have to keep on document.ready code as it is and then add function updateGraph outside document.ready (keep all variable at global level). Also modify updateGraph, here you need to call .replot() on plot1 variable as you are only changing data and not other setting.
put id to li like this : <li id="updateGraph">YOUR TAKE-HOME PAY</li>
See below code :
// declare variable outside document.ready
var plot1;
var storedData;
$(document).ready(function () {
storedData = <?php echo $_SESSION['chart_data'] ?>;
jQuery.jqplot.config.enablePlugins = false;
plot1 = jQuery.jqplot('savings_expense', [storedData],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer
},
legend: {
show: true,
rendererOptions: {
numberRows: 6
},
placement: 'outside',
location: 's',
marginTop: '15px'
}
}
);
$('#updateGraph').click(function(){updateGraph();});
});
function updateGraph() {
var newVal = <?php echo $_SESSION['chart_data'] ?>;
plot1.destroy();
plot1.series[0].data = newVal;
plot1.replot(true);
}

Related

Passing values to chart.js - Laravel

I am able to fetch data from database which i want to pass to a chart.js. With the code below,
the chart displays ["{items: Nike}",total:20"},"{items: Addidas}",total:40"}] in the xaxis.
But then i want it to display like
categories: ['Nike', 'Addidas'];
Controller
$items = DB::table('items_tbl')->select('name', DB::raw('count(*) as total'))->groupBy('name')
->get();
return view('home',compact('items'));
HTML
<script>
var items_pass = #json($items)
</script>
JS
xaxis: {
categories: [JSON.stringify(items_pass)],
axisBorder: {
show: true,
color: '#bec7e0',
},
axisTicks: {
show: true,
color: '#bec7e0',
},
},

Queried Data as Datapoints on Chart.js

I am trying to plot chart using Chart.JS based on my data from database. Here number of Labels and their values will come directly from the query result. Here is my code:
<script type="text/javascript">
window.onload = function () {
<?php
function getValsOfCategoryLabels(){
$yValsWithLabels = "";
......
// some codes to make query on db and get result in $queryResult variable
......
......
foreach($queryResult as $data){
$x0 = $data0['name'];
$total = $data0['total'];
$yValsWithLabels = $yValsWithLabels. "{y: ".$total.", label: \"".$x0."\"}, ";
}
return $yValsWithLabels;
}
?>
var categoryLabelsNdVals = [<?php echo getValsOfCategoryLabels() ?>];
var hourlyCategoryBarChart = new CanvasJS.Chart("columnchartContainer", {
animationEnabled: true,
axisX: {
labelFontSize: 16
},
axisY: {
title: "",
labelFontSize: 13
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center",
fontSize: 16
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "Name of Category",
dataPoints: categoryLabelsNdVals
}
]
});
hourlyCategoryBarChart.render();
Now for the given datapoints (which is in "{y: Some_Value, label: Some_Name}" format) I am not getting any chart as output, unless I explicitly declare all the y-axis values and label names myself, which fails reflect database info.
What is the right way to accomplish my objective?

HighCharts with Dynamic Data not working

I have a ASP.NET MVC project with SignalR.
I have a page with a HighChart and the script looks like this:
$(function () {
window.Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 10
},
title: {
text: 'GMAS Queues'
},
xAxis: {
type: 'datetime',
tickInterval: 500,
labels: {
enabled: false
}
},
yAxis: {
title: {
text: 'Queue Count'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Processing Queues'
}]
});
});
$.connection.hub.logging = true;
// Reference the auto-generated proxy for the hub.
var chartData = $.connection.processingQueuesHub;
// Create a function that the hub can call back to display messages.
chartData.client.updateQueueCounts = function (data) {
//$.each(data, function(i, item) {
// // Add the message to the page.
// $('#chartDataLog').append('<li><strong>' + htmlEncode(item.QueueName)
// + '</strong>: ' + htmlEncode(item.Length) + '</li>');
//});
// set up the updating of the chart.
var series = chart.series[0];
$.each(data, function (i, item) {
if (item.QueueName == "Queue A") {
var x = Date.parse(item.Date),
y = item.Length;
series.addPoint([x, y], true, false);
}
});
};
However, I see the graph but not the points.
The strange part is the series data points are there:
Anyone know why HighCharts is not rendering the points?
Thanks, Bill N
I have to thank my good friend and co developer for figuring this out. He is a smarter and braver man than me. :) He went to the highcharts source and found that the highcharts breaks if you add to the graph series before the initial animation is completed. The animation is why the clip-rect is zero-width (it animates from zero to full width over 1s when you first create the chart). You end up adding a point to the series before this animation even really starts. This kills the animation but it doesn’t fix the width of the clip-rect. The fix is to add animation is false for the series.
series: [{ name: 'Processing Queues', data: [], animation: false }]
It looks like you are not defining what your chart.series is until it is created. The line in your ajax is as follows and its not waiting for DOM ready:
var series = chart.series[0];
But you do not define chart until $(document).ready(function () {.... Try keeping your chart object in scope of your ajax.

flot doesn't draw bars chart

I tried with my other two scripts(line chart and pie chart) but the flot doesn't draw the bars chart... can you help me with this...I think the error is in the javascript..
The library:
<script src="js/jquery.flot.min.js"></script>
<script src="js/jquery.flot.pie.min.js"></script>
<script src="js/jquery.flot.stack.js"></script>
<script src="js/jquery.flot.resize.min.js"></script>
Here is the printdata db call:
[["junio",390],["julio",125],["agosto",50]]
Here is the script in graficayear.php:
<?php
include 'includes/configs.php';
$sql = $conn->prepare("SELECT DATE_FORMAT(start, '%M') AS mdate, SUM(honorario) AS total_mes
FROM CITAS WHERE YEAR(current_date) GROUP BY mdate DESC");
$sql->execute();
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
$datayear[] = array($row['mdate'],(int) $row['total_mes']);
}
?>
Here is the code in chartyear.php:
<?php include 'graficayear.php'; ?>
<script type='text/javascript' charset='utf-8'>
$(function () {
$.plot(
$("#baryear"),
[{
data : <?php echo json_encode($datayear);?>,
color: '#012D4C',
bars: { show: true, fillColor: '#4682b4', barWidth: (15*24*60*60*1000), align: 'center' }
}],
{
grid: { color: '#012D4C' },
xaxis: {
mode: 'time',
tickDecimals: 0,
tickSize: [1,'month'],
autoscaleMargin: 0.001
}
}
);
});
</script>
And the DIV with the ID:
<?php include 'chartyear.php'; ?>
<div id="baryear" style="width: 320px; height: 300px;"></div>
here is how my chart look like until now:
And this is the data I need to show inside of the bars chart:
You need to read the documentation on the expected data formats more carefully. Here you've specified an xAxis of type time but then have given it categories. You have to pick one way or the other.
So, given the format of you json data, here the shortest path to do what you want:
// given your data
var datayear = [["junio",390],["julio",125],["agosto",50]];
// split it into a data array and a ticks array
var data = [], ticks = [];
for (var i = 0; i < datayear.length; i++) {
data.push([i,datayear[i][1]]); // note that the x value is numeric
ticks.push([i,datayear[i][0]]); // and that the x value is matched to a "category"
}
$.plot(
$("#baryear"),
[{
data : data,
color: '#012D4C',
bars: { show: true, fillColor: '#4682b4', align: 'center' }
}],
{
grid: { color: '#012D4C' },
xaxis: {
ticks: ticks
}
});
Fiddle here.
Produces:

Loading PHP inside JS array using setInterval and jQuery load

The code below displays a pie chart using flot charts. It works perfectly but I need to place the data generated (abcdata) dynamically using PHP and then use a setInterval to refresh the data every 5 seconds. The data is not showing in index.php and the pie chart disappears. I believe it has got something to do with the var abdata variable being loaded via jQuery but I'm not sure how to solve it.
My intention is to load the data (abdata) via PHP and refresh the data every few seconds.
// Code in index.php
setInterval(function() {
$(".test").load("test.php");
}, 1000);
// Code in the test.php file:
var abdata = [
{ label: "B", data: 90}, // The data values are queried using PHP and SQL
{ label: "C", data: 112},
{ label: "A", data: 112}
];
if($("#chart").length)
{
$.plot($("#chart"), abdata,
{
series: {
pie: {
innerRadius: 0.5,
show: true
}
},
legend: {
show: false
},
colors: ["#f29020","#434343", "#3fbed3"]
});
}
I would be grateful if anyone could help out! Thanks in advance!
Instead of loading data using load(), you can use ajax() to return the abdata value as json and then use that value.
// Code in index.php
setInterval(function() {
$.ajax({
type:"GET",
url:"test.php",
success:function(response) {
var abdata = $.parseJSON(response);
if($("#chart").length)
{
$.plot($("#chart"), abdata,
{
series: {
pie: {
innerRadius: 0.5,
show: true
}
},
legend: {
show: false
},
colors: ["#f29020","#434343", "#3fbed3"]
});
}
}
});
}, 1000);
// Code in the test.php file:
$abdata = array(
array( 'label'=> "B", 'data'=> 90), // The data values are queried using PHP and SQL
array( 'label'=> "C", 'data'=> 112),
array( 'label'=> "A", 'data'=> 112)
);
echo json_encode($abdata);

Categories

Resources