Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto Refresh document title?

I have tried many ways to have the page title automatically update every 3 seconds so the title can display how many unread messages they have.

Here is what I have tried:

setInterval(function() {
        document.title = "<?php echo $inboxcc; ?>";
    }, 3000);

and

$(function() {
setInterval(function() {
     $(this).attr("title", "<?php echo $inboxcc; ?>");
    }, 3000);
});

But none of them work.

like image 323
Andy Avatar asked Dec 07 '22 19:12

Andy


1 Answers

You need to refresh the data from the server each time you want fresh data, since the PHP block is only executed once per page view (on the server). Make a PHP page like this:

<?php
  // data.php
  // Grab the user from the session and calculate the 'unread messages' value
  $user['inboxcc'] = the_unread_messages_value;
  echo json_encode($user);
?>

Then pull the number dynamically like this:

var updater = function() {
    $.getJSON('data.php',function(jsonuser){
        document.title = jsonuser.inboxcc;
        setTimeout(updater,3000);
    });
};

setTimeout(updater,3000);

Note that I use setTimeout instead of setInterval, since you can't be sure every request will return in 3 seconds. Using setTimeout is better in general.

like image 180
Jens Roland Avatar answered Dec 10 '22 12:12

Jens Roland