0
I need to create a way to notify system users each time a database table receives a new record.
I’m using as a basis an example published here Server Push: Long Polling but I’m having some problems, the first of which is that analyzing the browser network it makes several requests until the browser crashes... and as a consequence it keeps repeating the database registration list, it follows the code of the server.php:
<?php
include ('config.php');
include ('database.php');
$requestedTimestamp = isset ( $_GET [ 'entry' ] ) ? (int)$_GET [ 'entry' ] : time();
while ( true )
{
$stmt = $PDO->prepare("SELECT * FROM notifications WHERE entry >= :requestedTimestamp" );
$stmt->bindParam(':requestedTimestamp', $requestedTimestamp);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ( count( $rows ) > 0 ){
$json = json_encode( $rows );
echo $json;
break;
}else{
sleep( 2 );
continue;
}
}
and this is the js:
function getContent( entry )
{
var queryString = { 'entry' : entry };
$.get('./database/server.php', queryString, function( data ) {
var obj = jQuery.parseJSON( data ),
string = "";
// lista obj json
for (var i in obj)
{
var classy = obj[i]['readable'] == 0 ? 'new-notfication' : '';
string += '<div class="table notification-table '+classy+'">';
string += '<div class="td"><img src="img/default/default-user-image.png" alt=""></div>';
string += '<div class="td">';
string += '<p><a href="#"><strong>'+obj[i]['title']+'</strong></a></p>';
string += '<p>'+obj[i]['msg'].substr(0,66)+'...</p>';
string += '</div>';
string += '<div class="td"><a href="#" class="close"><span class="fa fa-times" aria-hidden="true"></span></a></div>';
string += '</div>';
$('#entry').append(string);
}
//reconecta
// getContent(data);
});
}
getContent();
in the first execution of the function it repeats the record and brings 6 values.