Question

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.

Était-ce utile?

La solution

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

Autres conseils

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);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top