I already asked about this subject on how can I convert my basic polling script into a long polling structure and a user from that post said there is two parts to long polling. The client side structure and the server side
structure and he suggested I reask this question but this time referencing more on how I can implement long polling on the server side. Since he already provided the long polling structure example in the client side by JavaScript. So how can I implement long polling on the server side for the file called
check-for-new-records.php?
Here is the rest of my code to better understand what I mean.
index.php
<style>
#label{
margin: 0;
color: red;
font-weight: bold;
}
</style>
<script>
document.addEventListener('DOMContentLoaded',function(){
/**********************************************************************
Check for a new record amount in the data base
**********************************************************************/
//Client side structure of long-polling
function checkForNewRecords() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
document.querySelector('#output').innerHTML = xhr.responseText;
setTimeout(checkForNewRecords, 0);
}
}
xhr.open('POST', 'check-for-new-records.php');
xhr.send();
}
checkForNewRecords()
});
</script>
<p id='label'>Total records in the database in real time in basic polling</p>
<div id='output'></div>
check-for-new-records.php
<?php
//Long polling in the server side code... How???
$db_servername= 'localhost';
$db_username='jd';
$db_password= '1234';
$db_name= 'test';
$db_connect= new mysqli($db_servername,$db_username,$db_password,$db_name);
$db_query= "SELECT COUNT(id) AS id FROM example";
$db_result= $db_connect->query($db_query);
$db_row= $db_result->fetch_object();
$total_records= $db_row->id;
?>
<style>
#total-records{
margin-top: 0;
}
</style>
<p id='total-records'><?php echo $total_records; ?></p>