Search code examples
phpjqueryajaxpartial-page-refresh

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.


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