How to periodically fetch data from psql table - javascript

I am fetching data from a psql table and passing it to javascript as json array for display as a time series chart. The data passed needs to be in the from of an array.
As the data in the table is updated periodically, I need to constantly fetch the data from psql e.g. every 15 minutes and pass updated array to javascript.
I search but so far I couldn't any solution. My question is how can I fetch data from psql periodically.
Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<script>
var Device_Data;
var time, batt;
var timeArray = [];
var battArray = [];
var N = 12;
for (i = 0; i < N; i++) {
timeArray.push(0);
battArray.push(0); }
function dspChrt(Device_Data) {
console.log(Device_Data[0].date_time);
console.log(Device_Data[1].battery_voltage_mv);
time = Device_Data[0].date_time;
batt = Device_Data[1].battery_voltage_mv;
timeArray.shift();
timeArray.push(time);
battArray.shift();
battArray.push(batt);
</script>
</head>
<body>
<?php
require("Connection.php");
$stmt = $conn->prepare("Select date_time, battery_voltage_mv FROM measuring_device_statuses order by date_time desc limit 12");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$WData = $stmt->fetchAll();
/*
echo "<pre>".print_r($WData, true)."</pre>";
die();
*/
?>
<script>
var WData = <?php print_r(json_encode($WData));?>;
//console.log(WData);
dspChrt(WData);
</script>
</body>
</html>

Keep you data fetch php script in some file "fetch.php" and through javascript set interval function call it periodically for example this code prints alert every 3 secs.
setInterval(function(){ alert("Hello"); }, 3000);

You can use AJAX for this purpose.
HTML
<div id="myDiv"></div>
JavaScript
<script>
window.onload = function(){
loadDoc();
SetInverval(loadDoc, (10000 * 60 * 15)); // Perform function every fifteen minutes
}
function loadDoc() {
var div = document.getElementById("myDiv"); // Get Div
div.innerHTML = ""; // Set to nothing
var xhttp = new XMLHttpRequest(); // Create new XML object
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) { // If successful
div.innerHTML = this.responseText; // Display result
}
};
xhttp.open("GET", "loadDoc.php", true);
xhttp.send();
}
This should be in your PHP file, named loadDoc.php or whatever you choose to replace it to.
<?php
require("Connection.php");
$stmt = $conn->prepare("SELECT date_time, battery_voltage_mv FROM measuring_device_statuses ORDER BY date_time DESC LIMIT 12");
$stmt->execute();
//$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$WData = $stmt->fetchAll();
$stmt->close();
echo "<pre>".print_r($WData, true)."</pre>";
die();
?>

Related

how to refresh div without refreshing all php data

I would think this is simple but cannot figure it out for the life of me.. I want to refresh a div without refreshing everything.. I have a timer on each image that counts down from 24 hrs to 0 then disappears.. it all works but I cant seem to just refresh the timer div..
My php -
$date = date('Y-m-d H:i:s');
$sql = "SELECT * FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$path = $row['path'];
$user = $row['user'];
$update = $row['update_date'];
$timeFirst = strtotime($date);
$timeSecond = strtotime($update);
$timeSecond = $timeSecond + 86400;
$timer = $timeSecond - $timeFirst;
if($timer <= 0){
}else{
echo '<img id="pic" src="/v2/uploads/'.$path.'"/>';
echo '<div id="user">#'.$user.'</div>';
echo '<div id="timer">'.$timer.' </div>';
}
}
}
I would like to refresh just the timer at 1 second intervals not the images.. I know I can use ajax to call it from an external file that loads all the content also as far as I know..Still new at this. *side not this is chopped up code for the example not all of it.
As per my comment, you could do something like this:
Add class "timer" to your #timer element (if you have more than one #timer element, use different ID for each element).
Create php script which returns new $timer whenever it's called:
ajax-timer.php
<?php
/* include file where $conn is defined */
$response = array();
$date = date('Y-m-d H:i:s');
$sql = "SELECT * FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$update = $row['update_date'];
$timeFirst = strtotime($date);
$timeSecond = strtotime($update);
$timeSecond = $timeSecond + 86400;
$timer = $timeSecond - $timeFirst;
if($timer > 0) {
//Add just timer to response array
$response[] = $timer;
}
}
}
//Return json response and handle it later in ajax:
echo json_encode(array(
'result'=>empty($response) ? 0 : 1,
'data'=>$response));
die();
Request data from ajax-timer.php with $.ajax and populate data when response is received:
timer-update.js
var ajaxTimerThread = 0;
var ajaxTimerRunning = false;
function ajaxTimerRun() {
//Prevent running function more than once at a time.
if(ajaxTimerRunning)
return;
ajaxTimerRunning = true;
$.post('ajax-timer.php', {}, function (response) {
ajaxTimerRunning = false;
try {
//Try to parse JSON response
response = $.parseJSON(response);
if (response.result == 1) {
//We got timer data in response.data.
for(var i = 0; i < response.data.length; i++) {
var $timer = $('.timer').eq(i);
if($timer.length) {
$timer.html(response.data[i]);
}
}
}
else {
//Request was successful, but there's no timer data found.
//do nothing
}
//Run again
ajaxTimerThread = setTimeout(ajaxTimerRun, 1000); //every second
}
catch (ex) {
//Could not parse JSON? Something's wrong:
console.log(ex);
}
});
}
$(document).ready(function() {
// Start update on page load.
ajaxTimerRun();
})
Toss your existing php code into a separate .php file
Then use a jquery method called load() to load that php file into your div.
$(document).ready(function() {
$("#div_ID_you_want_to_load_into").load("your_php_file.php");
var pollFrequency = function() {
if (document.hidden) {
return;
}
$("#div_ID_you_want_to_load_into").load('your_php_file.php?randval='+ Math.random());
};
setInterval(pollFrequency,18000); // microseconds, so this would be every 18 seconds
});
Now, within this code above is something is not needed, but can be helpful, and that is the if (document.hidden) {return;} which is basically a command to the browser that if the browser tab is not in-focus do not fire off the setInterval poll.
Also a good idea to keep in the randval= math stuff, just to make sure there is no caching.

Ajax response text is always 1

I am sending two variables to my php page for calculation then echoing the end result back. My response text always equals one.
The Javascript:
var xhttp = new XMLHttpRequest();
xhttp.open("GET","calc.php?w1="+ftest+"&w2="+ltest,true);
xhttp.onreadystatechange = function() {
if(xhttp.readyState==4)
{
var dog = xhttp.responseText;
alert(dog);
}
};
xhttp.send(null);
}
The php:
I set the end var to a random number here just to test if my math was causing the problem.
$startdate = $_GET['w1'];
$endDate = $_GET['w2'];
$workingdays = 239;
echo $workingDays;
Set $workingDays directly to 10 ( random number ). If it is not 10, then you are clearly not seeing the result of that echo statement.
1 is often used as the output to native PHP functions such as isset
You're case is wrong.
$workingdays = 239;
echo $workingDays;
Make it workingDays (with capital D) in both places.
Always use isset() for receiving data and you are using variable $workingdays for declaration and for echo $workingDays, take care of these things. I hope this will work for you.
$startdate = '';
$endDate ='';
if(isset($_GET['w1']))
{
$startdate = $_GET['w1'];
}
if(isset($_GET['w2']))
{
$endDate = $_GET['w2'];
}
$workingdays = 239;
echo $workingdays;
die;
Try adding this variable in your ajax code just to make a test if in the server side is receiving the data you sent using get method.
var ftest = 1;
var ltest = 2;
I assumed that your ajax code is inside the a function let say myfunction and you have a link like this link
Here is the full implementation of the code assuming that your filename is index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ajax</title>
</head>
<body>
link
<script type="text/javascript">
function myfunction () {
var ftest = 1;
var ltest = 2;
var xhttp = new XMLHttpRequest();
xhttp.open("GET","calc.php?w1="+ftest+"&w2="+ltest,true);
xhttp.onreadystatechange = function() {
if(xhttp.readyState==4) {
var dog = xhttp.responseText;
alert(dog);
}
};
xhttp.send(null);
}
</script>
</body>
</html>
and Calc.php
<?php
$startdate = $_GET['w1'];
$endDate = $_GET['w2'];
$workingdays = 239;
$result = $startdate + $endDate;
echo "$result";
?>
In this example you alert will equal to 3 it be same in your code
Hope this will help

Updating javascript array with click when new mysql data comes in

I am using the following code to send mysql database content into a javascript array. This works fine when I start the page, but when the database gets a new entry, the new entries are not added to the array when I rerun this bit of code - unless I reload the entire page.
<p><button onclick="save_image()">Send image</button></p>
<script type="text/javascript">
function save_image(){
var userName =
<?php
$conn = new mysqli(.........."); //connect to database
$d = mysqli_query($conn, "SELECT name FROM canvas_data" );
$usernames = array();
while( $r = mysqli_fetch_assoc($d) ) {
$usernames[] = $r['name'];
}
echo json_encode( $usernames );
?>;
console.log(userName)
}
</script>
I realize there are other pages about this topic, but I didn't know how to apply them to my case. If you have some ideas. Thanks.
If you want to get information from the database without reloading the page, you'd need to do an Ajax request to retrieve the information.
Something like this would work:
PHP - ajaxendpoint.php
<?php
$d = mysqli_query($conn, "SELECT name FROM canvas_data" );
$usernames = array();
while( $r = mysqli_fetch_assoc($d) ) {
$usernames[] = $r['name'];
}
echo json_encode( $usernames );
?>
JavaScript
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText); //log the response from the database
//if the PHP is returning a JSON object, you can parse that:
var myArray = JSON.parse(xhttp.responseText);
}
}
xhttp.open("GET", "ajaxendpoint.php", true);
xhttp.send();
}
HTML - index.html
<button onclick="getData()">
Load Data via Ajax
</button>
Here is another example Ajax request in this JS Fiddle: https://jsfiddle.net/igor_9000/77xynchz/1/

Pull down updates when user click on updates

Hello people please help me with this! what i want to achieve is similar to twitter update notification bar that displays the number of new tweets and when you click on it; it drops the latest tweets on the previous tweets. i have been banging my head over this for days now, Here is what i tried.
//feed.php
<?php
session_start();
$cxn = mysqli_connect('localhost','root','','my_db');
$query = "SELECT insertion_time FROM feeds ORDER BY insertion_time DESC LIMIT 0,1";
$result = mysqli_query($cxn, $query) or die (mysqli_error($cxn));
$latest_feed = mysqli_fetch_assoc($result);
$_SESSION['latest_id'] = $latest_feed['insertion_time'];
$latest_news = $_SESSION['latest_id'];
echo $check = <<<JS_SCRIPT
<script>
interval = setInterval(function(){
check_update($latest_news);
},5000);
</script>
JS_SCRIPT;
?>
<script src='jquery.js'></script>
<script>
function check_update(old_feed)
{
$.post('server.php',{get_num_update: old_feed},function(data){
$("#update_bar").html(data);
}); //checks for number of updates
$.post('server.php',{retrieve_update: old_feed},function(data){
$("#hidden_div").html(data);
}); //retrieves the update into a div
}
$(function(){
$("#update_bar").click(function(){
$("#hidden_div").prependTo("#news_feed_container").fadeIn(500);
});
});
</script>
//server.php
if(isset($_POST['get_num_update']) && !empty($_POST['get_num_update']) && is_numeric($_POST['get_num_update']))
{
$old_feed = $_POST['get_num_update'];
$query = "SELECT id FROM feeds WHERE insertion_time > $old_feed ORDER BY insertion_time DESC";
$exec = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$num_updates = mysqli_num_rows($exec);
echo ($num_updates > 0) ? $num_updates.' new updates' : '';
}
if(isset($_POST['retrieve_update']) && !empty($_POST['retrieve_update']) && is_numeric($_POST['retrieve_update']))
{
while($result = mysqli_fetch_assoc($exec))
{
extract($result);
echo <<<HTML
//inserting the variable into html
HTML;
}
}
//
when the user clicks on the update_bar div which will be displaying something like '5 new updates' i want the update to pull down the latest feed from the hidden div, so everything doesn't really work as i would expect someone please help me out
Not tested, but it should approximately work...
//feed.php
<?php
session_start();
$cxn = mysqli_connect('localhost','root','','my_db');
$query = "SELECT insertion_time FROM feeds ORDER BY insertion_time DESC LIMIT 0,1";
$result = mysqli_query($cxn, $query) or die (mysqli_error($cxn));
$latest_feed = mysqli_fetch_assoc($result);
$_SESSION['latest_id'] = $latest_feed['insertion_time'];
$latest_news = $_SESSION['latest_id'];
echo $check = <<<JS_SCRIPT
<script>
// made the parameter of check_update a js variable and not hard coded in PHP
var latest_new=$latest_news;
// add a temp js variable for the last feed received (but not displayed)
var last_received=$latest_news;
interval = setInterval(function(){
check_update(latest_news);
},5000);
</script>
JS_SCRIPT;
?>
<script src='jquery.js'></script>
<script>
function check_update(old_feed)
{
// change your AJAX request to deal with JSON data and received several informations (number of new feed, insertion time of the last one)
$.post('server.php',{get_num_update: old_feed},function(data){
$("#update_bar").html(data.number_recents+" new updates.");
last_received=data.last_time;
},'json');
$.post('server.php',{retrieve_update: old_feed},function(data){
$("#hidden_div").html(data);
}); //retrieves the update into a div
}
$(function(){
$("#update_bar").click(function(){
$("#hidden_div").prependTo("#news_feed_container").fadeIn(500);
latest_new=last_received;
});
});
</script>
//server.php
if(isset($_POST['get_num_update']) && !empty(get_num_update']))
{
// header to serve JSON data
header('application/json');
$old_feed = $_POST['get_num_update'];
// request the number of new feed and the mst recent insertion time
$query = "SELECT count(*) as number,max(insertion_time) as last_time FROM feeds WHERE insertion_time > $old_feed ORDER BY insertion_time DESC";
$exec = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$feed_info = mysqli_fetch_assoc($exec);
//write the JSON data
echo '{"number_recents":'.$feed_info['number'].',"last_time":'.last_time.'}';
} else if(isset($_POST['retrieve_update']) && !empty($_POST['retrieve_update']) && is_numeric($_POST['retrieve_update']))
{
while($result = mysqli_fetch_assoc($exec))
{
extract($result);
echo <<<HTML
//inserting the variable into html
HTML;
}
}

show result from PDO query every 10 seconds

Not sure if this is possible but here goes, I have a basic PDO query that stores the results in a array.
<?php
// configuration
$dbtype = "";
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$title = 'PHP AJAX';
// query
$sql = "SELECT * FROM thankyou";
$q = $conn->prepare($sql);
$q->execute(array($title));
$q->setFetchMode(PDO::FETCH_BOTH);
// fetch
while($r = $q->fetch()){
echo"<br>";
print_r ($r);
}
?>
Now the bit I can't get my head around, I have also never used JavaScript. Can I rotate through the results to show one at a time for 5-10 seconds then show another? It can be random or in order, I'm not fussed. I found this, which works, but can't figure out how to get the array into it. I am aware one is client side and one is server side.
<script type="text/javascript">
var rotatingTextElement;
var rotatingText = new Array();
var ctr = 0;
function initRotateText() {
rotatingTextElement = document.getElementById("textToChange");
rotatingText[0] = rotatingTextElement.innerHTML; // store the content that's already on the page
rotatingText[1] = "need to write PDO array here";
setInterval(rotateText, 5000);
}
function rotateText() {
ctr++;
if(ctr >= rotatingText.length) {
ctr = 0;
}
rotatingTextElement.innerHTML = rotatingText[ctr];
}
window.onload = initRotateText;
</script>
and this is were the results are shown
<span id="textToChange">this is were the result is displayed</span>
If I need to do it a totally different way, it's not a problem if someone can point me in the correct direction.
If you're not so familiar with JavaScript, I also suggest using some JS library for the task. In fact, Prototype.js has a class exactly for this purpose: http://prototypejs.org/doc/latest/ajax/Ajax/PeriodicalUpdater/index.html
A working example: http://www.tutorialspoint.com/prototype/prototype_ajax_periodicalupdater.htm
i decided to use AJAX to call a seprate PHP page in the end and works fine this is the updated page.
<script type="text/javascript">
$(function() {
getStatus();
});
function getStatus() {
$('div#status').load('thankyou.php')//Thankyou being the page the query is on
setTimeout("getStatus()",5000);//refreshes every 5 seconds
}
</script>
The query itself is a standard PDO
$query = $db->query("SELECT * FROM `thankyou` ORDER BY RAND() LIMIT 1
Thanks for the pointers all.

Categories

Resources