I need to refresh a div every few seconds on my below index.php
page.
<?php
session_start();
if (! check_write()) {
redirect('testlogin.php');
return;
}
if (file_exists('lmt.json')) {
$lmt = json_decode(file_get_contents("lmt.json"), true);
}
?>
<!doctype html>
<html lang="en">
<head>
<title>Home</title>
</head>
<body>
<div>
<h1>Website Title</h1> <a href="logout.php">Logout</a> </div>
<div>
<p>Welcome back,
<?= $_SESSION['user_id'] ?>!</p>
</div>
<!-- How can I refresh below div every x seconds? -->
<div>
<?php if (isset($lmt)) { ?>
<p>Last modified by <?= $lmt['fname']; ?> at <?= $lmt['ts']; ?></p>
<?php } ?>
</div>
<form method="post">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" name="submit" value="Save Data"> </form>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(function() {
$('form').submit(function(e) {
e.preventDefault();
$.post({
url: 'save.php',
data: $(this).serialize(),
}).done(response => {
response = JSON.parse(response);
if(response.message) {
alert(response.message);
}
});
});
});
</script>
</body>
</html>
Below is the div I want to refresh every X seconds. As of now it just gets the value from $lmt
variable and show it to the user but I want to refresh that div every X seconds by reading from lmt.json
file and then show fname
and ts
variable.
<!-- How can I refresh below div every x seconds? -->
<div>
<?php if (isset($lmt)) { ?>
<p>Last modified by <?= $lmt['fname']; ?> at <?= $lmt['ts']; ?></p>
<?php } ?>
</div>
How can I do this efficiently?
2
Answers
If you’re just looking for a quick way to get this done and over with I would implore you to check on w3schools.com. Here’s an interesting look into what you might want from your site. It’s an insight on the setTimeout() and setInterval() function from vanilla JS. Happy coding!
JS Timing
Write two seperate files
index.php
(It contains the div that you want to refresh) andfilehandle.php
(file contents that you should recieve).index.php
filehandle.php
change the value of
update_time
value inindex.php
to your desired value (it refers to update everyupdate_time
seconds).