简体   繁体   中英

How to send alert to client when database is updated, like facebook chat

I want to send alert to client who is using the website only when saome field gets updated. i know how to regularly check for database updations with silent ajax calls. I only want to trigger an ajax call when there is information updated. In other Words, the mysql server will send an alert to client that some table row is changed so that the client will trigger the ajax call and the info can be retrieved.

You can use websockets with PHP. Take a look at Thruway . Thruway uses WAMP which supports a publish and subscribe message model. You could use the AutobahnJS JavaScript library on the browser side to subscribe to events published by PHP when it makes database updates.

Disclaimer: I am a project maintainer for Thruway.

The best way to do so is the use of realtime technologies such as nodejs, however there is a way around in php (with javascript/jquery). I once develop a chat with php and javascript. All i did is set five seconds interval in javascript to listen to the server for any new message and append it to the chat box.

如果您的Web服务器是节点,请使用websockets,否则,另一种方法是每30秒左右进行长时间轮询(使用setInterval)以查询数据库。

you can use this code:

function checkUpdate()
{
 jQuery.ajax({
   type: "POST",
   url: "your.php",
   data: "name=currentUser&",   //our any other data you want to check
   success: function(msg){
     if(msg.indexOf('no Updates') !== -1 )
         {
            alert( "You have an update" );
     }
 });
}

You can use the above code to call and get response from your.php and will alert when the response doesnt contain "no Updates." I suggest you to do this periodically by this code every 2 minute:

window.setInterval("checkUpdate()", 2*60*1000); // our any other period you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM