0

I am needing to automatically refresh my PHP page. I have a PHP page that is returning the current database time. However, this is requiring me to refresh the page in order for me to update.I need a better way of updating this PHP variable that does not include refreshing the page. Here's what I have so far:

$time = current_time($db);
echo '<p>$time</p>'

How can I accomplish this? EDIT: I've changed my code but it still won't auto-refresh: index.php

<div id="#timeLocation">

<script>
var updateTime = function(){
$.ajax({url: "time.php", success: function(response){
$('#timeLocation').html(response);
}});
setInterval(updateTime, 1000);
}

updateTime();

</script>


</div>

time.php

 <?php 

 require_once('db.php');
 require_once('functions.php');

$time = current_time($db);
echo $time[0];


?>
Chris
  • 73
  • 1
  • 2
  • 8
  • 1
    AJAX is the answer. – Jay Blanchard Jan 25 '17 at 16:44
  • Could you provide a simple example to help me get started? I've read that other people have said AJAX as well but I'm not sure how to incorporate it into my code. – Chris Jan 25 '17 at 16:47
  • 1
    There are lot's of basic AJAX tutorials online. – Jay Blanchard Jan 25 '17 at 16:48
  • Possible duplicate of [What is the difference between client-side and server-side programming?](http://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – u_mulder Jan 25 '17 at 16:49

3 Answers3

2

index

<html>
<head>
    <meta charset="UTF-8">
    <title>Time</title>
</head>
<body>

<div id="time">

</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
        setInterval(function(){
            $.ajax({url: "time.php", success: function(response){
                $('#time').html(response)
            }});
        }, 1000);
</script>
</body>
</html>

time.php

<?php

$time = date("g:i:s a");
echo $time;

this isnt the exact answer but it will help you along the way, watch when using ajax the way ive displayed though, sending a request everysecond could eventually slow down your server with enough time

Kenziiee Flavius
  • 1,918
  • 4
  • 25
  • 57
0

With javascript you can run a function every tot. second:

setInterval(function,60000)

The function that you call should be an ajax request to a PHP page, that return the current hour. In my opinion you can implement all with only javascript, calling a function every second that update the hour field.

ollaw
  • 2,086
  • 1
  • 20
  • 33
0

While ajax has been told in the comments, here is a pseudo implementation of it:

<div id="#timeLocation"></div>

<script>
const updateTime = function(){
     $.ajax({url: "time.php", success: function(response){
        $('#timeLocation').html(response);
    }});
    setInterval(updateTime, 1000);
}
updateTime();
</script>

This will update the timeLocation div with the content of time.php every second.

Antony
  • 1,253
  • 11
  • 19