Ajax add JSON value for each chart
I have an Arduino over an ethernet shield giving out a value every second via AJAX. I would like to calculate this value in Flot . This requires the value to be put in JSON like this
[[epochtimestamp, value], [epochtimestamp, value]]
So I was wondering if you could help me use JavaScript / AJAX (or PHP if you think it's appropriate) to get this value every second and add it to JSON inside a .txt file (used to store previous values ), so Flot can read all values and create a time-based plot, but update the plot every second via AJAX.
This is the basic process that should happen every second.
- Arduino Updates Value (I did this bit)
- Javascript or PHP file that adds this value to JSON with a timestamp
- The fleet updates and displays the new value.
Here is some code I started, but it will need to be called AJAX every second and won't do all the work.
<?php
$file = 'data.txt';
$webpage = 'test.txt';
$t = time(); // Open the file to get existing content
$current = file_get_contents($file);
$data = file_get_contents($webpage);
// Append a new person to the file
if ($current < 1) {
$current .= "[[" + $t + "," + $data + "]";
} else {
$current .= ", " + "[" + $t + "," + $data + "]";
} // Write the contents back to the file
file_put_contents($file, $current);
echo $current;
?>
I'm not sure if it would be easier to work with Javascript / AJAX?
source to share
Take a look at the source flo for a real-time update example.
You can call your PHP script via AJAX from the browser, your client code should look like this.
// Initialize your empty plot
var plot = $.plot("#myPlot", [], {
series: {
shadowSize: 0 // Drawing is faster without shadows
},
yaxis: {
min: 0,
max: 100
},
xaxis: {
show: false
}
});
function update() {
// Make an ajax call to your script to get data provided by your script
// Which reads that data.txt from Arduino.
$.ajax({
url: "yourhost/yourscript.php",
context: document.body
}).done(function(response) {
// Get the ajax response
data = response;
// If data is not null, set your plot data.
if (data != null)
plot.setData(data);
// Draw the plot.
plot.draw();
// Re-invoke update.
update();
});
}
// Initial call to the update func.
update();
source to share