Sajjad Khan
Sajjad Khan

Reputation: 345

Automatically update time in PHP using Ajax

how automatically update the time in PHP using Ajax..the below command work by refreshing the page by hit f5 or reload button..

echo date('s');

or if it is necessary to update time by only using AJAX in php..

Upvotes: 0

Views: 7205

Answers (2)

Daniel
Daniel

Reputation: 598

So basically this can be done using php and AJAX. Lets say you have two files index.php and timer.php. You can achieve your desired results by doing the following.

In Index.php

 <?php

echo "<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset='UTF-8'>
        <meta name='viewport' content='width=device-width, initial-scale=1.0'>
        <script src='http://code.jquery.com/jquery.js'></script>
        <script>
         $(document).ready(function(){
             setInterval(_initTimer, 1000);
         });
         function _initTimer(){
             $.ajax({
                 url: 'timer.php',
                 success: function(data) {
                    console.log(data);
                     data = data.split(':');
                     $('#hrs').html(data[0]);
                     $('#mins').html(data[1]);
                     $('#secs').html(data[2]);
                 }
             });
         }
        </script>
    </head>
    <body>
        <span id='hrs'>0</span>:<span id='mins'>0</span>:<span id='secs'>0</span>
    </body>
</html>";

In timer.php

 <?php echo date('h:i:s A');

Upvotes: 1

Yes Kay Selva
Yes Kay Selva

Reputation: 584

You can use html5 server send event,The EventSource object is used to receive server-sent event notifications:

demo.php

<!DOCTYPE html>
<html>
<body>

<h1>Getting server updates</h1>
<div id="result"></div>

<script>
if(typeof(EventSource) !== "undefined") {
    var source = new EventSource("demo_sse.php");
    source.onmessage = function(event) {
        document.getElementById("result").innerHTML += event.data + "<br>";
    };
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>

</body>
</html>

demo_sse.php file

 <?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('s');
echo "data: The server time is: {$time}\n\n";
flush();
?> 

if you have doubt let me know

Upvotes: 3

Related Questions