I'm trying to show a notifications counter updated upon javascript.
I have tried to use the following to refresh the html:
At the top of the page declaring the counter value (how many messages user has):
<?php
$nc = notificationCount($user_data['id']);
$ng = $user_data['id'];
if ($nc >= 1){
$nstyle = 'style="display:block;"';
} else {
$nstyle = 'style="display:block;"';
}
?>
Then the standard initial loading of the counter value that works properly:
<li id ="ndiv" class="nav-item pt8" <?php echo $nstyle; ?>><a href="javascript:void(0);" data-toggle="modal" data-target="#myModal" onclick="showUser(<?php echo $ng;?>)">
<i class="fa fa-bell f18 cr"></i><span id ="nc" class="f16 cr"><?php echo $nc;?></span></a>
</li>
In attempt to keep the counter refreshing every 5000 I tried the following, but it does not refresh despite the increase in value taking place.
<script>
function checkNotification() {
console.log(' each 5 second...');
document.getElementById("nc").value = "<?php echo $nc;?>";
}
var myVar = setInterval(checkNotification, 5000);
</script>
A PHP page returns a result to the client. Once the page returns its result, it's done. You can't have a PHP page return a result every so often. But, what you can do is call out to a PHP page ( using AJAX ) that returns the notification count at regular intervals using setInterval()
.
let notifications = document.getElementById("notifications"); // This would be a function that calls a .php page to get // the notification count returned. You could use AJAX // to make that call. function simulateServerCode(){ return Math.floor(Math.random() * 100); } let timer = setInterval(function(){ notifications.textContent = simulateServerCode(); }, 5000);
<div>You have <span id="notifications"></span> notifications.<div>
You don't need the server side for showing the notifications.
Try this:
JS:
notificationsCount = document.getElementById("notificationsCount");
numberOfNotification = 10; // example
showing = setInterval(function(){
notificationsCount.textContent = numberOfNotificaton;
}, 5000);
HTML:
<h1>
Number of notifications <h1 id="notificationsCount"></h1>
</h1>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.