I am currently playing around with ajax trying to create a script that returns a value from a database that updates in realtime.
HTML
<!doctype html>
<html lang="en-gb">
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="ajax.js"></script>
<script type="text/javascript">
$(document).ready(function() {
liveReload('#ajax');
});
</script>
<meta charset="utf-8">
</head>
<body>
<section id="ajax">0</section>
</body>
</html>
PHP
<?php
class Ajax
{
public static function grab()
{
try
{
$db = new PDO('mysql:host=localhost;dbname=ajax', 'root', null);
$rq = $db->query('select setting, value from test');
return $rq->fetchAll(PDO::FETCH_ASSOC)[0];
}
catch (PDOException $e)
{
echo $e->getMessage();
}
}
}
echo json_encode(Ajax::grab());
JQUERY
(function() {
liveReload = function(element) {
$.ajax({
url: 'ajax.php',
dataType: 'json',
cache: false,
success: function(data)
{
$(element).html(data['value']);
setTimeout(liveReload, 1000);
}
})
}
})(jQuery);
The problem is that this value is only being updated in the page once despite the function returning the new values as they are updated.
As I said in the comment: you don’t pass the element into setTimeout, so it looses the reference to the element and effectively shows nothing