I have a weather station that uploads data to my website via PHP. I have created an app for it that I want to display a chart on. I have google charts producing an image on my website that the app then references. The problem is the only way I've been able to produce the image is to load the webpage myself in my browser. Ideally I'd like my server to update the png image every time my weather station uploads data.
My weather station uploads data via a simple PHP get request.
If I visit this page I can view a PNG base 64 image and it uses an AJAX query to save a copy of the image onto my server.
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "getdata.php",
data: 'q=' + "<?PHP echo $_GET['ID']; ?>",
dataType: "json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var options = {
title: "Wind Chart",
vAxis: {title: 'Wind Speed (Knots)',
viewWindow: {
min: 0
},
gridlines: { count: 5 },
},
legend:'bottom',
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'ready', function () {
chart_div.innerHTML = '<img src="' + chart.getImageURI() + '">';
console.log(chart_div.innerHTML);
$.ajax({
type: "POST",
url: "savechartimage.php",
data:{d: chart.getImageURI(), ID: "<?PHP echo $_GET['ID']; ?>" }
})
});
chart.draw(data, options);
}
</script>
</head>
<body>
<div id='chart_div'></div>
</body>
</html>
where the savechartimage.php is below
<?PHP
$data = $_POST['d'];
$ID = $_POST['ID'];
file_put_contents('app/'.$ID.'chart.png',
base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data)));
?>
The closest way I've gotten to automatically save the PNG is by including the script on the php page that my weather station uploads its data via GET requests. This loads the chart and means unnecessary data transfer back to my weather station.
How can I call this script to run in the background when triggered by an upload from my weather station?