简体   繁体   中英

How do we make our page refresh data once every minute with ajax jquery?

How do we implement a timer to send an ajax request to refresh data (like new entries from other users on database) every one minute. I am using $.ajax from jquery.

My intention is to send the time where there was the last update so the server does not send repeated data. Only rows created from after that time.

My server script is php.

For Sending Date and Time You can use this function

        var date    = new Date();
        var date    = date.getUTCFullYear() + '-' +
        ('00' + (date.getUTCMonth()+1)).slice(-2) + '-' +
        ('00' + (date.getUTCDate()).slice(-2) + ' ' + 
        ('00' + date.getUTCHours()).slice(-2) + ':' + 
        ('00' + date.getUTCMinutes()).slice(-2) + ':' + 
        ('00' + date.getUTCSeconds()).slice(-2);

Above will format the date and time in mysql format which you pass through variable to mysql query and then use setInterval to pass current time after every minute

    setInterval(function(){ 
     $.ajax({
     type:"POST",
     data:"Time="+ date,     
     url:"serverRef",
     success: function(data){
         // On success 
                           }
     });              

     },60000);

Note: You can also use same technique in Server side as well

setInterval with jQuery's post would work wonders. Make sure if you have a lot of visitors, remember to cache, otherwise you can rack up a lot of queries without noticing, which in the past I've noticed can overwhelm some hosts and essentially take you offline.

var ajax = window.setInterval(function(){
    $.post('path/to/my/script.php', function(data){
         if(data == "stop")
         {
             clearInterval(ajax);
             return;
         }

         $('#statistics').html(data);
    });
}, 60000);

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