how to check if database is updated with php and ajax?

孤街醉人 提交于 2019-12-01 05:29:08

问题


I am making a chat box, everything is working fine, except the update thing. I am currently refreshing the page every 3 sec to check any new messages, but it will surely cause a massive load on server and is not elegant.

What i want is, chat box will check for new messages only when database is updated, rather than the timer of checking database after every 3 sec


回答1:


You want AJAX push (server sends update to client only when there's something new). See an example here: http://provatosys.com/bid.html

Something like this would elaborate the request from the client:

function sendRequest(uid){
    var xmlhttp;
    var myUserId="";
    myUserId=uid;

    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            displayInChat(xmlhttp.responseText)//do stuff (process response, display message)
        }
    }

    xmlhttp.open("GET","process_request.php?userid="+uid,true);
    xmlhttp.send();

    setTimeout("sendRequest("+uid+")",1000); //poll every second
}

Now you want to delay the reply from your server (process_request.php) until there's something to send (using something like while (($msg=new_msgs()) === false) {sleep(timeout);} for example) or the request times out and a new poll is send from the client (setTimeout("sendRequest("+uid+")",timeoutinmillisecs);). This is called Long polling and for applications like chats is more efficient than replying with an empty response.

You can find more info here: How do I implement basic "Long Polling"?

and here: Make AJAX call wait for event in php

and here: Comet (programming)

[EDIT] As a very much needed and more efficient alternative to long polling, now all major browsers support websockets. The RFC6455 has entered the status of (proposed) standard in 2011 (which means it has exited draft status and hasn't had any changes since). The best implementation in PHP is probably Ratchet (as far as I know the most up to date with the standard by far). Here is a tutorial on how to build a web chat using it: http://socketo.me/docs/hello-world



来源:https://stackoverflow.com/questions/11907372/how-to-check-if-database-is-updated-with-php-and-ajax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!