jQuery setInterval update PDO content - javascript

I'm wanting to run a jquery script that updates a content box every so often. I want the contents on this box to be from my database.
So far I have this, which isn't much, but not sure how the best way would be to replace the content. This is how my approach would be, but i'm sure its incorrect and there is a better way, also this does not work anyways.
<div id="list"> List here </div>
<script>
$(document).ready(function() {
setInterval(function(){ updateList(); }, 8000);
});
function updateList(){
$('#list').html(
<?php
$sql = "SELECT * FROM list WHERE enable = 1 ORDER BY id DESC";
$stm = $dbh->prepare($sql);
$stm->execute();
$u = $stm->fetchAll();
foreach ($u as $list) {
?>
"<?php echo $list['name']; ?>";
<?php
} ?>
);
}
</script>
My question is, how would I be able to do this? Thanks

You need to execute an Ajax function that call PHP server side operations like this (with <ul><li> list to show all elements separeted, but optional) :
list.php
<?php
function get_list() {
$sql = "SELECT * FROM list WHERE enable = 1 ORDER BY id DESC";
$stm = $dbh->prepare($sql);
$stm->execute();
return $stm->fetchAll();
}
if($_GET['update']) {
$html = '<ul>';
foreach(get_list() as $element) {
$html. = '<li>'.$element['name'].'</li>';
}
echo $html . '</ul>';
die();
}
?><html>
<head>
<title>...</title>
Some css and js...
</head>
<body>
<div id="list">
</div>
<script>
$(document).ready(function() {
setInterval(function(){
$.get('list.php?update=1', function(data) {
$('#list').html(data);
});
}, 8000);
});
</script>
</body>
</html>

As stated in my comment :
PHP is just a preprocessor
Therefore I recommend the use of AJAX and a separated PHP script to do the job (and an <ul>):
getEnabledsNames.php
<?php
$sql = "SELECT * FROM list WHERE enable = 1 ORDER BY id DESC";
$stm = $dbh->prepare($sql);
$stm->execute();
$u = $stm->fetchAll();
$u = array_map(function($elem){
return $elem['name'];
}, $u);
header('Content-Type: application/json');
echo json_encode($u);
?>
The JS code
let interval;
$(document).ready(()=>{
interval = setInterval(updateFromDb, 8000);
});
function updateFromDb(){
$.get(
"getEnabledsNames.php",
(data)=>{
$("#list > ul").html("");
data.forEach(e=>{
$("#list > ul").append(`<li>${e}</li>`);
});
}
).fail(/* function to handle failure here */);
}
The HTML
<div id="list">
<ul></ul>
</div>

Try This
var gtimer;
$(document).ready(function() {
clearInterval(gtimer);
gtimer = window.setInterval(function() {
clearInterval(gtimer);
updateList();
},8000);
});

Related

How can I trigger PHP if a MySQL gets a new highest ID?

Im trying to make my Webpage do an action (in this case play a sound) on the event of the highest ID (auto_increment) in my SQL table increasing, which happens when a new user is registered. E.g. : 3 users registered, highest ID = 3. When a new user registers, highest ID = 4. Webpage echos/plays sound if this happens.
The Js and PHP, respectively:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#show').load('data.php')
}, 3000);
});
</script>
<?php
include ('../includes/dbh.inc.php');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT * FROM signs WHERE id = (SELECT MAX(id) FROM signs)");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row['firstName'];
echo $row['lastName'];
echo $row['inOrOut'] . '<br>';
$numId = $row['ID'] . '<br>';
echo $numId;
}
$value = 1;
$value = $numId;
if ($value < $numId) {
//echo '<script type="text/javascript">play_sound();</script>';
echo "increased";
}
else
echo "nothing detected";
}
}
?>
As you can tell, I tried doing something with comparing the last and the newest ID value but failed miserably.
My attempt would be to store an initial value for oldID and then comparing this to newID before replacing it.
You can't do that only with PHP. But you could do it like this:
If you have a website, you set the current highest ID in the output of php. You can use javascript to call another php script every 5 minutes (or any other time span you find meaningful) that gives you back the current highest number. If the number from the php script is higher, than the number you have in javascript, you can let javascript play a sound for you.
Assuming your php script returns an id like this:
{"id":4}
an example for the javascript call would be this:
<html>
<head></head>
<script>
let highestId = 2;
window.setInterval(async function(){
const response = await fetch('http://localhost/jstest/index.php');
const myJson = await response.json();
console.log(console.log(myJson.id));
if (highestId < myJson.id) {
highestId = myJson.id
// here you can play your sound
$s = document.getElementById('myId');
$s.innerHTML = highestId;
}
}, 5000);
</script>
<body>
<span id="myId">0</span>
</body>
</html>
You can use a cookie variabale to do this. Set the cookie value using php and send the cookie value with php file call. This way you can identify a new highest id.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
var id = getCookie("highest_id");
$('#show').load('data.php?id='+id)
}, 3000);
});
</script>
Add set cookie in the code if the value is changed.
<?php
include ('../includes/dbh.inc.php');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT * FROM signs WHERE id = (SELECT MAX(id) FROM signs)");
if ($result->num_rows > 0) {
$numId = 0;
if ($row = $result->fetch_assoc()) {
$numId = $row['id'];
}
$value = $_GET['id'] ?? 0;
if ($value < $numId) {
//echo '<script type="text/javascript">play_sound();</script>';
echo "increased";
setcookie("highest_id", $numId, time() - 3600);
} else {
echo "nothing detected";
}
}
?>
Note the points :
In PHP : setcookie("highest_id", $numId, time() - 3600);
In Script : getCookie("highest_id");

how can print data from database in javascript

i want to print date column from database in javascript code
this is the original javascript code i want to change date countdown
<script type="text/javascript">
$(document).ready(function() {
$('#countdown').countdown('2017/07/10 06:32:11', function(event) {
$(this).html(event.strftime('%H:%M:%S'));
});
});
</script>
and this code after edit :
<?php
$count = $DB_con->prepare("SELECT * FROM `auction` WHER ORDER BY id DESC");
$count->execute();
foreach ($count->fetchAll() as $rowL)
{
?>
<script type="text/javascript">
$(document).ready(function() {
var countdw;
countdw = = <?php echo $rowL['dateauction']; ?>
$('#countdown').countdown(document.write(countdw), function(event) {
$(this).html(event.strftime('%H:%M:%S'));
});
});
</script>
<?php
}
?>
If you only have one value from the database, you don't need to loop anything, although I can't imagine you have one whole table dedicated to one row unless you have a bunch of rows chronicled, in which case you probably should limit to one row to return. At any rate, it's likely it should look something more like this:
<?php
# You probably just need to limit 1 and only select the column you need
$query = $DB_con->prepare("SELECT `dateauction` FROM `auction` ORDER BY id DESC LIMIT 1");
$query->execute();
# Just fetch without a loop
$row = $query->fetch(PDO::FETCH_ASSOC);
?>
<script type="text/javascript">
$(document).ready(function() {
// You should probably have quotes and a semicolon, also only one equal sign
var countdw = '<?php echo $row['dateauction'] ?>';
$('#countdown').countdown(document.write(countdw), function(event) {
$(this).html(event.strftime('%H:%M:%S'));
});
});
</script>

Trouble with auto refresh in table

I have this index.php file to show some stuff in tables from loop:
$sql = 'SELECT id FROM usertbl';
$stmt = $hund->runQuery($sql);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);
<?php foreach ($row as $runloop) { ?>
<table><th> <?php echo $runloop['id']; ?> </th></table>
<?php } ?>
However, I wish to have auto refresh for those tables. So I have this new file data.php and a updated index.php:
data.php:
$sql = 'SELECT id FROM usertbl';
$stmt = $hund->runQuery($sql);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);
print_r($row);
index.php:
<div id="show"></div>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#show').load('data.php')
}, 3000);
});
</script>
<?php foreach ($row as $runloop) { ?>
<table><th> <?php echo $runloop['id']; </th></table>
<?php } ?>
This will refresh and print the output in the above <div>:
<div class="show"></div>
And it works great, but I don't really have any clue how to put that inside the loop for the tables, just as the first index.php file. Any suggestions of a direction to take in this matter?
You can use ajax to call data.php and return the response in json format for a better approach
Try:
js
function populate(){
var items= [];
$.ajax({
url: 'data.php',
type: 'GET',
dataType: 'json',
success: function(data){
//do something with data here
console.log(data);
//loop through data and push to array
$.each(data, function(i,v){
items.push('< th >'+v+'< /th >');
});
//join array and append to table
$('#sampleTable tbody').html(items.join(','));
},
error: function(err){
console.log(err.responseText);
}
});
}
//call populate every 10 secs (example only , you can change to how many seconds you like)
setTimeout(function(){
populate();
},10000);
data.php
$sql = 'SELECT id FROM usertbl';
$stmt = $hund->runQuery($sql);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);
echo json_encode($row);
In this line you forgot to close <?php ...
Possibly that's why foreach loop doesn't work correctly
<?php foreach ($row as $runloop) { ?>
<table><th> <?php echo $runloop['id']; ?></th></table>
<?php } ?>
Put these lines in data.php where print_r() is.

AJAX get() data

I have a block of jQuery which uses the $.get() method in a setInterval(). I don't understand how to get data from the second URL to the jQuery code.
Jquery:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
setInterval(function() {
$.getJSON("check_time.php", function(update) {
if (update) {
$("#slideshow").load("phppage.php");
}
});
}, 600000);
</script>
PHP - check_time.php
<?php
require_once('connect_pdo.php');
header('Content-type: application/json');
$stmt = $conn->prepare("$sqlst = $conn->prepare("SELECT COUNT(*) AS count
FROM ads
WHERE lastupdate > NOW() - INTERVAL 10 MINUTE");
$sqlst->execute();
$row = $sqlst->fetch();");
$stmt ->execute();
$row = $stmt ->fetch();
$update = $row['count'] > 0;
$updtstatus = json_encode($update);
echo "$updtstatus";
?>
I am not getting the variable from check_time.php to the update variable in function(update).
Small alter in php page
$updtstatus = json_encode(array('count'=>$update));
echo $updtstatus;
Now your JSON is in fact something like this {"count":"true"}.
So change your if statement slightly.
$.getJSON("check_time.php", function(update) {
if (update.count===true) {
$("#slideshow").load("phppage.php");
} else {
console.log("No results");
}
});
This fiddle simulates the above answer
Your jQuery functions expects data to be returned in JSON format, so simply do so :) I've also found some flaws within your PHP code. This should do the trick:
$.get('check_time.php', function(data) {
console.log(data); // Console logging is always good
if (data.status) {
alert('Load slideshow');
}
});
check_time.php
<?php
require_once('connect_pdo.php');
$json = []; // The JSON array which will be returned
$stmt = $conn->prepare("SELECT COUNT(*) AS count FROM ads WHERE lastupdate > NOW() - INTERVAL 10 MINUTE");
$stmt->execute();
$json['status'] = (bool) $stmt->rowCount(); // Status is either false (0) or true (> 0)
echo json_encode($json);

how can i get my script/jquery-ajax to continue responding to clicks?

Still a programming and markup newbie...
I have several little in/out button that reads and writes back from a mysql table to track whether different users are available or unavailable. But I can only click the button once to change the status. After that, it stops responding. How can I get it to just keep working? Thanks!!!!
list.php
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
$(".rating").on("click", function(){
var status = $(this).attr("id").substr(0,1);
var id = $(this).attr("id").substr(1);
var data = "id="+id+"&status="+status;
$.ajax({
type: "POST",
url: "rate.php",
data: data,
success: function(e){
$("#r"+id).html(e);
}
})
});
});
</script>
<style>.rating { cursor: pointer; }</style>
</head>
<body>
<?php
include ("headers.php");
$qq = mysql_query("SELECT * FROM $io");
while($rr=mysql_fetch_array($qq)){
$id = $rr["id"];
$content = $rr["status"];
include("buttons.php");
$list .= '<div style="border-bottom: 1px #32baed solid">'.$q[0].'
<div id="r'.$id.'"><img class="rating" id="'.$q[0].$id.'"
src="'.$color.'"> '.$status.'</div></div><br><br>';
}
echo $list;
?>
</body>
</html>
rate.php
<?php
include ("headers.php");
$id = $_POST["id"];
$status = $_POST["status"];
if($status == 0){
mysql_query("UPDATE $io SET status = 1 WHERE id='$id'");
}
else {
mysql_query("UPDATE $io SET status = 0 WHERE id='$id'");
}
include("buttons.php");
$list = '<img class="rating" id="'.$q[0].$id.'" src="'.$color.'"> '.$status;
echo $list;
?>
buttons.php
<?php
$q = mysql_query("SELECT status FROM $io WHERE id='$id'");
$q = mysql_fetch_array($q);
if($q[0]){
$color = "green.png";
}
else{
$color = "red.png";
}
?>
headers.php
<?php
$c = mysql_connect("localhost", "username", "password");
$db = mysql_select_db("likes", $c);
$io = 'io';
?>
Replace
$(".rating").on("click", function(){
With
$(document).on("click", ".rating", function(){
You have to do like this:
$(document).on("click", ".rating", function(){
//YOUR CODES HERE
});
And make sure that these codes are outside of document ready function.
Read the documentation for help on .on()

Categories

Resources