Reputation: 261
I have the following code that gets values from a database and does a simple line graph (Response time to an alert vs. UTC time). It works perfectly while static, but now I want to do obtain the data in "real time" (just to test it, for example obtain each element every 2 seconds, that are 2000 miliseconds). Here is the code that works in a static way:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM data";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>User</th><th>Zulu</th><th>Server Time</th><th>Sample</th><th>Response Time</th></tr>";
// output data of each row
$dataset1 = array();
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row[""]. "</td><td>" . $row[""]. "</td><td>" . $row[""]. "</td><td>" . $row[""]. "</td><td>" . $row[""]. "</td></tr>";
$dataset1[] = array(floatval($row[""]),intval($row[""]));
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
As we can see, the data is stored into the $dataset1 variable, and then I just have a simple script that plots it:
<script>
//put array into javascript variable
var dataset1 = <?php echo json_encode($dataset1); ?>;
var data = [
{
data: dataset1,
}
];
var options = {
};
$(function () {
$.plot($("#placeholder"), data,options);
});
</script>
My question is: How can I "toy" with this $dataset1 to PLOT it every 2000 ms?
And this is what I get:
Upvotes: 3
Views: 1461
Reputation: 3766
If you want it every 2 seconds you should use .setTimeout() as .setInterval() can be inaccurate.
You might need to tweek this to get the values to stick on each call of the getData function. The best way would be to somehow store them in the element being passed to the function.
I need you to post your HTML code if you want me to test this and create a JS FIDDLE for it.
(function($){
$(function(){ //document.ready
});
(function getData(element){
var xval = xval ? xval : 0;
var yVal1 = Math.floor(Math.random()*11);
var yVal2 = Math.floor(Math.random()*11);
var datum1 = [xVal, yVal1];
var datum2 = [xVal, yVal2];
var data = data ? data : [[],[]];
var plot = $.plot(element, data);
data[0].push(datum1);
data[1].push(datum2);
if(data[0].length>10){
data[0] = data[0].splice(1);
data[1] = data[1].splice(1);
}
xVal++;
plot.setData(data);
plot.setupGrid();
plot.draw();
}
setTimeout(function(){
getData(element);
}, 2000);
})($('#chart4'));
})(jQuery);
Upvotes: 3