Unable to autorefresh my chart using javascript - javascript

Chart is loading fine but I'm unable to autorefresh this chart, tried setInterval(drawChart, 10000); and is not working. Did I place the interval in the wrong position? function is drawChart.
function drawChart(candlestickChartDataOptions, candlestickChartData, chart_id) {
var data = google.visualization.arrayToDataTable(candlestickChartData, true);
var options = {
chartArea: {
left: 40,
top: 20,
width: "100%",
height: "70%"
},
legend:"none",
title:candlestickChartDataOptions.currency1+" price in "+candlestickChartDataOptions.currency2,
bar: { groupWidth: "70%" ,
}, // sets space between bars
candlestick: {
fallingColor: { strokeWidth: 0, fill: "#a52714" }, // red
risingColor: { strokeWidth: 0, fill: "#0f9d58" }, // green
}
};
var chart = new google.visualization.CandlestickChart(document.getElementById(chart_id));
chart.draw(data, options);
}
jQuery( document ).ready(function() {
jQuery( "select#chart_period_'.$chart_id.'" ).change(function() {
setCandlestickPeriod(candlestickChartDataOptions_'.$chart_id.', jQuery(this).val());
candlestickLoadData(candlestickChartDataOptions_'.$chart_id.', "'.$chart_id.'");
});
drawChart();
setInterval(drawChart, 10000);
});
</script>
<div id="<?php echo $chart_id; ?>"></div>
Also tried this and is not working too, the $chart_id is correct:
<script>
setInterval(function(){
$("<?php echo $chart_id; ?>").load(document.URL + " <?php echo
$chart_id; ?>");
}, 10000)
</script>
What went wrong? Please help thanks.

Related

Converting a HTML page to PDF

I want to convert a HTML page like the given one having a form in it to PDF using jsPDF, but the table isn't getting printed with all of the columns in it. So I am thinking to print it on a landscape page but I am confused with the size measurements. Can anyone help me to get it done correctly?
And this is how it gets printed:
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
<script>
(function () {
var
form = $('.form'),
cache_width = form.width(),
a4 = [595.28, 841.89]; // for a4 size paper width and height
$('#create_pdf').on('click', function () {
$('body').scrollTop(0);
createPDF();
});
//create pdf
function createPDF() {
getCanvas().then(function (canvas) {
var
img = canvas.toDataURL("image/png"),
doc = new jsPDF({
unit: 'px',
format: 'a4'
});
doc.addImage(img, 'JPEG', 20, 20);
doc.save('suman-html-to-pdf.pdf');
form.width(cache_width);
});
}
// create canvas object
function getCanvas() {
form.width((a4[0] * 1.33333) - 80).css('max-width', 'none');
return html2canvas(form, {
imageTimeout: 2000,
removeContainer: true
});
}
}());
</script>
<script>
/*
* jQuery helper plugin for examples and tests
*/
(function ($) {
$.fn.html2canvas = function (options) {
var date = new Date(),
$message = null,
timeoutTimer = false,
timer = date.getTime();
html2canvas.logging = options && options.logging;
html2canvas.Preload(this[0], $.extend({
complete: function (images) {
var queue = html2canvas.Parse(this[0], images, options),
$canvas = $(html2canvas.Renderer(queue, options)),
finishTime = new Date();
$canvas.css({ position: 'absolute', left: 0, top: 0 }).appendTo(document.body);
$canvas.siblings().toggle();
$(window).click(function () {
if (!$canvas.is(':visible')) {
$canvas.toggle().siblings().toggle();
throwMessage("Canvas Render visible");
} else {
$canvas.siblings().toggle();
$canvas.toggle();
throwMessage("Canvas Render hidden");
}
});
throwMessage('Screenshot created in ' + ((finishTime.getTime() - timer) / 1000) + " seconds<br />", 4000);
}
}, options));
function throwMessage(msg, duration) {
window.clearTimeout(timeoutTimer);
timeoutTimer = window.setTimeout(function () {
$message.fadeOut(function () {
$message.remove();
});
}, duration || 2000);
if ($message)
$message.remove();
$message = $('<div ></div>').html(msg).css({
margin: 0,
padding: 10,
background: "#000",
opacity: 0.7,
position: "fixed",
top: 10,
right: 5,
fontFamily: 'Tahoma',
color: '#fff',
fontSize: 12,
borderRadius: 12,
width: 'auto',
height: 'auto',
textAlign: 'center',
textDecoration: 'none'
}).hide().fadeIn().appendTo('body');
}
};
})(jQuery);
</script>

I want to create Stacked Chart from JSON in google chart

help, I want to create stacked chart from JSON in google chart, honestly my problem is var data = google.visualization.arrayToDataTable([ this is my codes
<?php
$tmp = array();
require "configdashboard.php";
/*
select the 3 columns of interest, assinging aliases for laziness purposes
*/
$sql = "SELECT devices.device_id AS device_id, devices.hostname AS hostname, devices.ip, devices.uptime, SUM(storage.storage_used) AS storage_used, SUM(storage.storage_free) AS storage_free , storage.storage_descr AS storage_descr
FROM storage
INNER JOIN devices ON storage.device_id = devices.device_id GROUP BY devices.device_id, storage.storage_descr";
$conn = mysqli_connect('localhost', 'root', '', 'monitoring');
$query = mysqli_query($conn, $sql);
$fetch = mysqli_fetch_assoc($query);
if ($stmt = $connection->query($sql)) {
while ($row = $stmt->fetch_assoc()) {
/* Add each row with named columns - which makes working with the JSON in Javascript easier IMO */
$tmp[] = array(
'device_id' => $row['device_id'],
'storage_used' => $row['storage_used'],
'storage_free' => $row['storage_free'],
'hostname' => $row['hostname'],
'storage_descr' => $row['storage_descr']
);
}
}
# create the JSON string
$json = json_encode($tmp);
//$json=json_encode( $fetch );
//print_r ($json);
?>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
var my_2d = <?php echo $json; ?>;
google.charts.load('current', {
packages: ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
if (Object.keys(my_2d).length > 0) {
for (i = 0; i < my_2d.length; i++) {
var data = google.visualization.arrayToDataTable([
['Task', 'Server Devices ' + my_2d[i].device_id + ' ' + my_2d[i].hostname],
['Used', parseInt(my_2d[i].storage_used)],
['Free', parseInt(my_2d[i].storage_free)]
]);
var options_fullStacked = {
isStacked: 'percent',
height: 300,
legend: {
position: 'top',
maxLines: 2
},
hAxis: {
minValue: 0,
ticks: [0, .3, .6, .9, 1]
}
};
var table = document.getElementById("table_chart");
if (i % 2 == 0) {
var tr = document.createElement("tr");
tr.setAttribute("class", "row_chart")
table.appendChild(tr)
}
var row_charts = document.getElementsByClassName("row_chart")
var td = document.createElement("td");
var div = document.createElement("div")
div.setAttribute("id", 'chart_div_' + i)
div.setAttribute("style", 'width: auto; height: auto; display: block; margin: auto;')
var lastTr = row_charts.length - 1
row_charts[lastTr].appendChild(td)
td.appendChild(div)
var chart = new google.visualization.BarChart(div);
chart.draw(data, options_fullStacked);
}
}
}
</script>
this is my database
and i want to create like this *note /, /run etc is storage_descr
but my output now
Looks like you have two separate series, Used and Free. You want one series as a stacked bar.
Try follwing the was they sample the table and chart setup here:
https://developers.google.com/chart/interactive/docs/gallery/barchart
var options = {
width: 600,
height: 400,
legend: { position: 'top', maxLines: 3 },
bar: { groupWidth: '75%' },
isStacked: true
};

Can't get Highstock "scroll" to work

trying to compare two sensor readings - the data is coming from thingspeak. I've got the zoom part working, but for some reason I cant get the scroll to work.
<script type="text/javascript">
// variables for the first series
var series_1_channel_id = 43330;
var series_1_field_number = 4;
var series_1_read_api_key = '7ZPHNX2SXPM0CA1K';
var series_1_results = 480;
var series_1_color = '#d62020';
var series_1_name = 'Zims Sensor';
// variables for the second series
var series_2_channel_id = 45473;
var series_2_field_number = 2;
var series_2_read_api_key = 'N12T3CWQB5IWJAU9';
var series_2_results = 480;
var series_2_color = '#00aaff';
var series_2_name = 'UVM30a';
// chart title
var chart_title = 'UV Sensors Zim / UVM30A';
// y axis title
var y_axis_title = 'UV Index';
// user's timezone offset
var my_offset = new Date().getTimezoneOffset();
// chart variable
var my_chart;
// when the document is ready
$(document).on('ready', function() {
// add a blank chart
addChart();
// add the first series
addSeries(series_1_channel_id, series_1_field_number, series_1_read_api_key, series_1_results, series_1_color, series_1_name);
// add the second series
addSeries(series_2_channel_id, series_2_field_number, series_2_read_api_key, series_2_results, series_2_color, series_2_name);
});
// add the base chart
function addChart() {
// variable for the local date in milliseconds
var localDate;
// specify the chart options
var chartOptions = {
chart: {
renderTo: 'chart-container',
defaultSeriesType: 'line',
zoomType: 'x', // added here
backgroundColor: '#ffffff',
events: { }
},
title: { text: chart_title },
plotOptions: {
series: {
marker: { radius: 3 },
animation: true,
step: false,
borderWidth: 0,
turboThreshold: 0
}
},
tooltip: {
// reformat the tooltips so that local times are displayed
formatter: function() {
var d = new Date(this.x + (my_offset*60000));
var n = (this.point.name === undefined) ? '' : '<br>' + this.point.name;
return this.series.name + ':<b>' + this.y + '</b>' + n + '<br>' + d.toDateString() + '<br>' + d.toTimeString().replace(/\(.*\)/, "");
}
},
xAxis: {
type: 'datetime',
scrollbar: {
enabled: true,
barBackgroundColor: 'gray',
barBorderRadius: 7,
barBorderWidth: 0,
buttonBackgroundColor: 'gray',
buttonBorderWidth: 0,
buttonArrowColor: 'yellow',
buttonBorderRadius: 7,
rifleColor: 'yellow',
trackBackgroundColor: 'white',
trackBorderWidth: 1,
trackBorderColor: 'silver',
trackBorderRadius: 7
},
title: { text: 'Date' }
},
yAxis: { title: { text: y_axis_title } },
exporting: { enabled: true },
legend: { enabled: true },
credits: {
text: 'ThingSpeak.com',
href: 'https://thingspeak.com/',
style: { color: '#D62020' }
}
};
// draw the chart
my_chart = new Highcharts.Chart(chartOptions);
}
// add a series to the chart
function addSeries(channel_id, field_number, api_key, results, color, name) {
var field_name = 'field' + field_number;
// get the data with a webservice call
$.getJSON('https://api.thingspeak.com/channels/' + channel_id + '/fields/' + field_number + '.json?offset=0&round=2&results=' + results + '&api_key=' + api_key, function(data) {
// blank array for holding chart data
var chart_data = [];
// iterate through each feed
$.each(data.feeds, function() {
var point = new Highcharts.Point();
// set the proper values
var value = this[field_name];
point.x = getChartDate(this.created_at);
point.y = parseFloat(value);
// add location if possible
if (this.location) { point.name = this.location; }
// if a numerical value exists add it
if (!isNaN(parseInt(value))) { chart_data.push(point); }
});
// add the chart data
my_chart.addSeries({ data: chart_data, name: data.channel[field_name], color: color });
});
}
// converts date format from JSON
function getChartDate(d) {
// offset in minutes is converted to milliseconds and subtracted so that chart's x-axis is correct
return Date.parse(d) - (my_offset * 60000);
}
</script>
​
<style type="text/css">
body { background-color: white; height: 100%; margin: 0; padding: 0; }
#chart-container { width: 800px; height: 400px; display: block; position:absolute; bottom:0; top:0; left:0; right:0; margin: 5px 15px 15px 0; overflow: hidden; }
</style>​
<!DOCTYPE html>
<html style="height: 100%;">
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.highcharts.com/stock/highstock.js"></script>
<script type="text/javascript" src="//thingspeak.com/exporting.js"></script>
</head>
<body>
<div id="chart-container">
// <img alt="Ajax loader" src="//thingspeak.com/assets/ajax-loader.gif" style="position: absolute; margin: auto; top: 0; left: 0; right: 0; bottom: 0;" />
</div>
</body>
</html>​
I would also like to get the chart updating automatically, so any help on that score would also be appreciated. The final issue I am having is trying to get the legend to display the sensor names properly: UV Index (red) should read "Zims Sensor" and UV Index (blue) should read "UVM30A"

Responsive Google Chart Data not working

Unfortunately I am not a developer, so I am trying to figure out how it works. I have some knowledge about PHP, HTML and CSS but unfortunately none about JavaScript. Below is my current code of Google Charts Data, it's imported by a module and the javascript code is in places inside the PHP file. Here is my code:
$js = "
google.setOnLoadCallback({$funcChart});
function {$funcChart}() {
var data = google.visualization.arrayToDataTable(".json_encode($data).");
var options = ".json_encode($options).";
var chart = new google.visualization.{$chart}(document.getElementById('{$container}'));
chart.draw(data, options);
}";
if(strpos($width, '%') !== false) {
JHtml::_('JABehavior.jquery');
$js .= "
jQuery(document).ready(function () {
jQuery(window).resize(function(){
{$funcChart}();
});
});
";
}
$doc = JFactory::getDocument();
$doc->addScriptDeclaration($js);
require JModuleHelper::getLayoutPath($module->module, $params->get('layout', 'default'));
}
How do I add a responsive function into the above code? The current chart looks weird on my page; http://goo.gl/v1GVWk
If you open the page and scroll to the "Trekking Map" tab then you will see the chart, but it looks very bad.
Try Using Following Code
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(initChartExpertBottom);
$(window).on("resize", function (event) {
initChartExpertBottom();
});
function initChartExpertBottom() {
var options = {
legend:'none',
width: '100%',
height: '100%',
tooltip: { isHtml: true },
chartArea: {left: "3%",top: "3%",height: "94%",width: "94%"},
colors: ['#7CB5EC', '#5C5C61','#16c104'],
pieHole: 0.50,
pieStartAngle: -90,
is3D: false,
pieSliceText: 'none',
};
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
["Hide" , (11+2)] //addition of value of all elements
]);
drawChartExpertBottom(data, options);
}
function drawChartExpertBottom(data, options) {
var tooltip = [
Math.round((11/(11+2))*100) + "%",
Math.round((2/(11+2))*100)+ "%",
"Hiii3",
];
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
var sliceid = 0;
function eventHandler(e){
chart.setSelection([e]);
try {
selection = chart.getSelection();
sliceid = selection[0].row;
}
catch(err) {
;
}
$(".google-visualization-tooltip-item-list li:eq(0)").css("font-weight", "bold");
$(".google-visualization-tooltip-item-list li:eq(1)").html(tooltip[sliceid]).css("font-family", "Arial");
}
google.visualization.events.addListener(chart, 'onmousedown', eventHandler);
google.visualization.events.addListener(chart, 'onmouseover', eventHandler);
chart.draw(data, options);
}
</script>
HTML for above script
<div id="piechart"></div>
Css for above code snippet
<style>
#piechart {
top: 0;
left: 0;
width:100%;
height:100%;
}
.google-visualization-tooltip{
display:table;
}
g{
cursor:pointer;
}
</style>

jQuery flot hover not working when user moves down the page

I am using jQuery flot. I can't seem to explain the bug well. But by the looks of it, the hover does not work when the user moves down to the page: Here's the video:
http://screencast.com/t/qZIjJ8jsi
Notice when i'm on top of my page the hover is working, but when I'll go down the page, then the hover on the points won't work.
My page is responsive(not sure if that's related, but just saying). Looks like this is a CSS problem. So here's my code:
var graphData = decodeURIComponent(jQuery("#graphData").val());
graphData = jQuery.parseJSON(graphData);
var visitors = new Array();
var totalVisitors = 0;
jQuery.each(graphData,function(index,value){
visitors[index] = [value[0],value[1]];
totalVisitors = totalVisitors + parseInt(value[1]);
});
jQuery(".date-figures").text(totalVisitors);
var visitor = $("#activeUsers"),
data_visitor = [{
data: visitors,
color: '#058DC7'
}],
options_lines = {
series: {
lines: {
show: true,
fill: true,
fillColor: "#E5F3F9",
color:"#058DC7",
},
points: {
show: true
},
hoverable: true
},
grid: {
backgroundColor: '#FFFFFF',
borderWidth: 0,
borderColor: '#CDCDCD',
hoverable: true
},
legend: {
show: true
},
xaxis: {
mode: "time",
},
yaxis: {
show:true
},
};
$.plot(visitor, data_visitor, options_lines);
function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css({
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 5,
padding: '2px 10px 2px 10px',
opacity: 0.8,
}).appendTo("body").fadeIn(200);
}
var previousPoint = null;
$('#visitor-stat, #order-stat, #user-stat,#activeUsers').bind("plothover", function (event, pos, item) {
if (item) {
if (previousPoint != item.dataIndex) {
previousPoint = item.dataIndex;
$("#tooltip").remove();
var d = new Date(item.datapoint[0]);
var day = parseDay(d.getDay());
var date = d.getDate();
var month = parseMonth(d.getMonth());
var year = d.getFullYear();
var tooltipWording = "<b>"+day+", "+month+" "+date+", "+year+"</b>";
tooltipWording += "<ul>";
tooltipWording += "<li>Visits: <b>"+item.datapoint[1]+"</b></li>";
tooltipWording += "</ul>";
showTooltip(item.pageX, item.pageY, tooltipWording);
}
}
else {
$("#tooltip").remove();
previousPoint = null;
}
});
});
What seems to be problem here? Your help will be greatly appreciated! Thanks! :)

Categories

Resources