Warn user about entering new data into the database

I donโ€™t know how to look for it, so Iโ€™m lost (the two topics that I saw here were closed).

I have a news site and I want to warn the user when new data is inserted into the database. I want to do this, like here in StackOverflow, where we warn you without reloading the page or like in facebook where you are warned of new messages / notifications without reloading.

What is the best way to do this? Is this some kind of timeout listener that constantly checks the database? It does not seem effective ...

Thanks in advance.

+4
source share
1 answer

You need javascript ajax and json and callback function to check. This can be done using push services, but PHP is bad with this and you need websockest, etc. Facebook uses timeouts. not sure about stackoverflow

refreshInterval = 500 refreshTimeout = setTimeout( getNotificationCounts, refreshInterval ); function getNotifications() { $.ajax({ url : 'path_to_your_php', type : 'POST', data: //put for exampel user_id but it cvan be handled by sesion as well dataType : 'json', success : function(data) { alert('You have'+ data.total +' new messages') refreshTimeout = setTimeout( getNotificationCounts, refreshInterval ); //this will check every half of second } }); } 

then in PHP, for example, you have a flag in the database with which you check whether the data is new to the database. Keep in mind formatting and proper sql execution

  $result=mysql_query("SELECT count(*) as total from myTable where user_id=$_POST['user_id'] AND is_read=0"); //note instad of $_POST you can use session if users are logged in, or however you are handling it $data=mysql_fetch_assoc($result); echo json_encode($data) 

;

After that, you can create another ajax call that marks messages as read as soon as the user clicks on them. or opens a list of dialogs or wahtever

 mysql_query("UPDATE myTable WHERE user_id=$_POST['user_id'] SET is_read=1"); 
+3
source

All Articles