With this script I can show a counter next to <i class="fas fa-bell mr-3"></i>
when it has data in db marked as status = unread
, and when I click on the icon <i class="fas fa-bell mr-3"></i>
it updates certain row to status = read
.
When I insert data into my table with status = unread
the $countNT
is incremented until it is working perfectly and that $countNT
is incremented without needing to refresh the page.
<i class="fas fa-bell mr-3"></i>
I send a POST request with Ajax to the file update.php
, and I can update the row that was previously status = unread
now would be status = read
and $countNT
zera. / p>
The problem is that the Ajax request for the update.php
file is only running once on the page, for example: if I updated the page 10s ago, and then a notification arrives, I can update the table in real time without needing to refresh the page, but if I had already called the file update.php
with Ajax on that page and then another notification arrives, it will not be possible to update my database, only I can update the database if I reload the page. Can someone explain me why?
html:
<div>
<ul class="navbar-nav textoPerfilDesk dropMenuHoverColor">
<li class="nav-item dropdown pr-2 dropleft navbarItem ">
<a class="nav-link dropdown-toggle-fk" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fas fa-bell mr-3"></i>
</a>
<div class="dropdown-menu dropdown-menu-fk py-3" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item dropMNitemNT" href="um-link">
<span class="d-flex">
<img class="imgNT" src="img/1.jpg">
<span class="pl-2 pt-1">
titutlo
</span>
</span>
</a>
</div>
</li>
</ul>
<span class="text-white divCountNT" id="datacount"></span>
</div>
script:
<script>
$(document).ready(function(){
$("#datacount").load("select.php");
setInterval(function(){
$("#datacount").load('select.php')
}, 1000);
});
$(document).on('click', '.fa-bell', function (){
$.ajax({
type: "POST",
url: "update.php"
}).done(function() {
$("#datacount").load("select.php");
});
});
</script>
select.php:
<?php
require_once 'db.php';
if(!isset($_SESSION))session_start();
if(isset($_SESSION['user_id'])) {
$user_id = $_SESSION['user_id'];
}
$status = 'unread';
$sql = $conn->prepare("SELECT * FROM noti WHERE status = :status AND user_id = :user_id");
$sql->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$sql->bindParam(':status', $status, PDO::PARAM_STR);
$sql->execute();
$countNT = $sql->rowCount();
echo $countNT;
$conn = null;
?>
update.php:
<?php
require_once 'db.php';
if(!isset($_SESSION))session_start();
if(isset($_SESSION['user_id'])) {
$user_id = $_SESSION['user_id'];
}
$status = 'read';
$sql = $conn->prepare("UPDATE noti SET status = :status WHERE user_id = :user_id");
$sql->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$sql->bindParam(':status', $status, PDO::PARAM_STR);
$sql->execute();
$countNT = $sql->rowCount();
echo $countNT;
$conn = null;
?>