I have a script that utilizes basic polling to display the total number of records in the database in real-time.
Can anyone provide an example of converting my code into a long polling structure using plain JavaScript? I've searched on Google but all the results show jQuery examples, which I find difficult to adapt to my situation. Here is a .gif screenshot showing my code in action for better understanding:
https://i.sstatic.net/pS0tV.gif
Below is my basic polling example code that needs to be transformed into long polling:
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
**********************************************************************/
function checkForNewRecords(){
var xhr= new XMLHttpRequest();
xhr.onreadystatechange= function(){
if(xhr.readyState == 4){
document.querySelector('#output').innerHTML= xhr.responseText;
}
}
xhr.open('POST','check-for-new-records.php');
xhr.send();
}
setInterval(function(){checkForNewRecords()},1000);
});
</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
$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>
I am looking to convert this into long polling with just plain JavaScript. Please avoid suggesting alternative methods as I am focused only on this specific conversion. It seems challenging to find help online regarding plain JavaScript solutions compared to the abundance of jQuery examples available. Not everyone prefers using libraries, and I have been disappointed by the lack of helpful responses on this particular topic. Your input would be greatly appreciated.