Charles Tester Charles Tester - 5 months ago 14
jQuery Question

AJAX check for update and php to refresh page

I am new to AJAX. Be gentle. I want to use ajax to check if there are any update in the database in the past ten minutes.

1) I have two sets of code for that. Please tell me which one is the better choice and why (if you have better code than mine, I am open for suggestions).

2) Secondly, the php script to check if update was during the past ten minutes, needs to update the first page which needs to be refreshed in case the update was in the last ten minutes, How do I do that?

Ajax option 1:

<script type="text/javascript" src=""></script>
<script type="text/javascript">
var auto_refresh = setInterval(function ()
}, 600000); // refresh every 600000 milliseconds


Ajax Option 2

function loadDoc() {
var xhttp = new XMLHttpRequest();"GET", "check_time.php", false);
document.getElementById("slideshow").innerHTML = xhttp.responseText;

PHP script to check for update


$currenttime = date('Y-m-d H:i:s');
$timelessten = date_modify($currenttime,"-10 Minutes");
$sqlst = $conn->prepare("SELECT `lastupdate` FROM `Ads`");
while($resultst = $sqlst -> fetch()){
$updatetime = $resultst["lastupdate"];
if($updatetime <= $timelessten){
//Refresh code here.

I have tried
header('location: phppage.php');
header('location: phppage.php'); exit();


You can check for new ads in the SQL query:

$sqlst = $conn->prepare("SELECT COUNT(*) AS count
                         FROM ads
                         WHERE lastupdate > NOW() - INTERVAL 10 MINUTE");
$row = $sqlst->fetch();

I suggest that you return a JSON response:

echo json_encode($row['count'] > 0);

Then in the Javascript code you can do:

setInterval(function() {
    $.getJSON("check_time.php", function(update) {
        if (update) {
}, 600000);