简体   繁体   中英

Popup message cannot display new update records from php mysql

I've made a popup message with auto-refresh function, so every few minutes the popup will appear to display the records. And it worked.

The following is the JavaScript code that auto refreshes:

$(document).ready(function() {
    setInterval(function() {
        $('#rtnotice').load('plugins/notice/n_notice_invoice.php').fadeIn("slow");
    }, 5000)
});

code of n_notice_invoice.php

    <script>
    $(document).ready(function(){
        $("#hide").click(function(){
            $("#noticearea").hide();
        });
    });
    </script>

<?php
    try{
    require_once "../../config/c_config.php";
    $db = dbConn::getConnection();
    $timestamp = $_REQUEST['term'];
    $sqlck = $db->prepare("SELECT COUNT(id_notice_alert) as ttlinv FROM str_notice_alert WHERE date_alert > '$timestamp'");
    $sqlck->execute();
    $resck = $sqlck->fetch(PDO::FETCH_ASSOC);
    if($resck['ttlinv'] == '0')
    {}else{
    ?>
    <div id="noticearea">
    <div id="modal">
            <div class="modal-content">
                <div class="header">
                    <div id="circle" align="center"><h1><?php echo $resck['ttlinv'];?></h1></div><div class="titlenotice"><h1>NOTICE ALERT<?php echo $timestamp; ?></h1></div>
                    <div class="break"></div>
                </div>
                <div class="copy">
                    <p>
                    <table width="100%" class="gridtable">
                    <tr><th>No</th><th>Name</th><th>Status</th><th>Location</th><th>Date</th></tr>
    <?php 
    $sqll = $db->prepare("SELECT * FROM str_notice_alert");
    $sqll->execute();
    while($resl = $sqll->fetch(PDO::FETCH_ASSOC)){ 
    ?>
    <tr><td align="center"><?php echo $resl['id_notice_alert']; ?></td><td><?php echo $resl['alert_name']; ?></td><td align="center"><?php echo $resl['alert_status']; ?></td><td align="center"><?php echo $resl['alert_location']; ?></td><td><?php echo $resl['date_alert']; ?></td></tr>
    <?php } ?>
    </table>
                    </p>
                </div>
                <div class="cf footer">
                    <button id="hide" class="btn">Close</button>
                </div>
            </div>
            <div class="overlay"></div>
        </div></div>
    <?php 

    $sqltrunc = $db->prepare("TRUNCATE TABLE str_notice_alert");
    $sqltrunc->execute();

    }$db = null;}
    catch (PDOException $e) {
    echo "Connection Error " . $e->getMessage();
    }
    ?>

After a popup message is displayed, it will display the file n_notice_invoice.php existing records and also delete the records via queries available. In any appearances. But the question is, why the records are not updated / changed. uUnless I refresh the file directly n_notice_invoice.php, and then auto-refresh displays the most recent data.

$timestamp = $_REQUEST['term'];

should be updated each time you call the page. You should load the page with Ajax passing $timestamp as a parameter instead of just loading it.

To get what you need can I suggest you to use long polling? PHP long polling or even better with node.js. For php for example the "server" page:

$timeStart = time();
// Create connection
$con = mysqli_connect('localhost','root','','polldb');

// Check connection
if (mysqli_connect_errno($con))
    die ('Failed to connect to MySQL: ' . mysqli_connect_error() );

// select where item is new
if(isset($_POST['timestamp'])){
    $timestamp = $_POST['timestamp'];
}else{
    // get current database time
    $row = mysqli_fetch_assoc(mysqli_query($con,'SELECT now() as now'));
    $timestamp = $row['now'];
}
$sql = "SELECT * FROM `notification` WHERE timestamp > '$timestamp'";

$newData = false;
$notifications = array();

// loop while there is no new data and is running for less than 20 seconds
while(!$newData && (time()-$timeStart)<20){

    // check for new data
    $result = mysqli_query($con,$sql);
    while($row = mysqli_fetch_assoc($result)){
        $notifications[] = $row;
        $newData = true;
    }
    // let the server rest for a while
    usleep ( 500000 );
}

// get current database time
$row = mysqli_fetch_assoc(mysqli_query($con,'SELECT now() as now'));
$timestamp = $row['now'];
mysqli_close($con);

// output
$data = array('notifications'=>$notifications,'timestamp'=>$timestamp);
echo json_encode($data);
exit;

and the client:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function(){
    pullNotification();
});

function pullNotification(timestamp){
    var data = {};
    if(typeof timestamp!='undefined')
        data.timestamp = timestamp;

    $.post('longpoll.php',data,function(msg){

        var newData = '';
        for(i in msg.notifications){
            newData+=msg.notifications[i].message+'\n';
        }
        if(newData!='')
            alert(newData);
        pullNotification(msg.timestamp);
    },'json');
}
</script>

This will check for database updates and will pop them up. Every 20 seconds it will renew the request. Obviously you have to adapt it to your needs.

I believie your issue comes from cached request (in Browser on in ajax itself) please try to disable ajax caching :

$(document).ready(function() {
    setInterval(function() {
       $.ajax({
        url: "plugins/notice/n_notice_invoice.php",
        cache: false
        })
        .done(function( data ) {
            $('#rtnotice').html(data).fadeIn("slow");
        });
    }, 5000)
});

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