KaoriYui
KaoriYui

Reputation: 922

New event notification without refreshing a page using PHP and AJAX

I show a notification to my users every time a new event is added to my database. I have a small icon on my top page and a red square to show the number of new events that were added. Now I just want to know what the best way is to display new events without refreshing the page.

notification element screenshot

Here is my code

<li><i class="fa fa-warning  fa-2x"></i>
    <?php if ($totalRows_event > 0) { ?>
        <span class="label label-danger blink"><?php echo $totalRows_event ?></span>
    <?php } ?>
</li>

My PHP query is basically when the total of events is > 0, display a <span> and the total inside, but this only shows when the page is refreshed or load.

I was looking at an AJAX request like the one below that will display the PHP query result into a inner html.

function testAjax() {
    var result = "";
    $.ajax({
        url: "data.php",
        async: false,
        success: function (data, textStatus) {
            $("#preview").html(data);
        },
        error: function () {
            alert('Not OKay');
        }
    });
    return result;
}
<li>
  <i class="fa fa-warning fa-2x"></i>
  <span class="label label-danger blink" id="preview"></span>
</li>

But how do I call the function every time a new event is added to my database without refreshing or loading the page? I think using a set interval or delay will slow my page because of frequent server queries so I am looking for other options.

Upvotes: 0

Views: 1709

Answers (1)

roiyu
roiyu

Reputation: 11

php:

 public function index()
    {
        if (!$_GET['timed']) exit();
        if (!$_GET['uid']) exit();
        date_default_timezone_set("PRC");
        set_time_limit(0);
        $uid = $_GET['uid'];
        while (true) {
            sleep(3); 
            $lastReadTime = M('readtime')->where(array('uid'=>$uid))->field('lasttime')->select();
            $result = M('message')->where(array('send_time'=>array('gt',$lastReadTime),'touid'=>$uid))->count();
            if($result){
                $data = array(
                    'message' => $result,
                );
                echo  json_encode($data);
                exit();
            } else { 
                usleep(1000);
                exit();
                //return;
            }
        }
        session_write_close();
    }

js:

 var cometURL = "{:U(GROUP_NAME.'/Comet/index')}"
    $(function () {
        (function longPolling() {
            //alert(Date.parse(new Date())/1000);
            $.ajax({
                url: cometURL,
                data: {"timed": Date.parse(new Date())/1000,"uid":$("#uid-hidden").val()},
                dataType: "json",
                timeout: 5000,
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    if (textStatus == "timeout") { 
                        longPolling();
                    } else { 
                        longPolling();
                    }
                },
                success: function (data, textStatus) {
                    if(data.message != 0){
                    $(document.body).append("<i class='iconfont'style='position: fixed;top: 28px;right: 30px;color: #2fa8ec;font-size: 20px'>&#xe61f;</i>");
                    $("#messagenum").html('message('+data.message+')');
                    }
                    if(data.image != 0){
                        $(document.body).append("<i class='iconfont'style='position: fixed;top: 28px;right: 30px;color: #2fa8ec;font-size: 20px'>&#xe61f;</i>");
                        $("#imagenum").html('New Image('+data.image+')');
                    }
                    if (textStatus == "success") { 
                        longPolling();
                    }
                }
            });
        })();
    });

i'm using THINKPHP and Jquery ,you can change it to your way.(AJAX LONG PULLING).or if your workspace is in linux,you can use swoole or workerman or websocket to make this.

Upvotes: 1

Related Questions