I am trying to make a notification system of incoming messages. For examlpe user stays on the page and he recieves in a block that he has 2 unread messages.
My client code:
(function getmess(){
var id = '<?=$MY_ID;?>';
$.ajax({
url:"notif.php",
data:{"id":id,},
type:"GET",
success: function(result){
$("#count").html(result);
}, dataType: "json",
complete: getmess,
timeout: 10000});
})();
My server code:
<?php
$mysqli = new mysqli('localhost', 'root', '', 'lc');
if (mysqli_connect_errno()) {
printf("error: %s
", mysqli_connect_error());
exit;
}
$MY_ID = $_POST['id'];
while (true) {
$result = $mysqli->query("SELECT COUNT(*) FROM messages WHERE user_get='$MY_ID' AND status='0' ");
if (mysqli_num_rows($result)) {
while ($row = mysqli_fetch_array($result)) {
echo $row[0]."";
}
exit;
}
sleep(5);
}
Everything works, but I have the problem that ajax requests are sent every 1 second and the lengh of these request is 1 second, and they overload the server.
I want to wait for a response from the server for at least 10 seconds in the case of a successful response to immediately send a new request, as well if the server does not respond within 10 seconds, ie in the database there is no change, then send a new query length of 10 seconds.
I think that is something wrong with server (may be sever loop), but i dont know how to improve this.