Hans Pede Hans Pede - 5 months ago 11
Ajax Question

Trouble with auto refresh in table

I have this

index.php
file to show some stuff in tables from loop:

$sql = 'SELECT id FROM usertbl';
$stmt = $hund->runQuery($sql);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);

<?php foreach ($row as $runloop) { ?>
<table><th> <?php echo $runloop['id']; ?> </th></table>
<?php } ?>


However, I wish to have auto refresh for those tables. So I have this new file
data.php
and a updated
index.php
:

data.php:

$sql = 'SELECT id FROM usertbl';
$stmt = $hund->runQuery($sql);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);
print_r($row);


index.php:

<div id="show"></div>

<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#show').load('data.php')
}, 3000);
});
</script>

<?php foreach ($row as $runloop) { ?>
<table><th> <?php echo $runloop['id']; </th></table>
<?php } ?>


This will refresh and print the output in the above
<div>
:

<div class="show"></div>


And it works great, but I don't really have any clue how to put that inside the loop for the tables, just as the first
index.php
file. Any suggestions of a direction to take in this matter?

Answer

You can use ajax to call data.php and return the response in json format for a better approach

Try: js

function populate(){
var items= [];
$.ajax({
 url: 'data.php',
 type: 'GET',
 dataType: 'json',
 success: function(data){

    //do something with data here
      console.log(data);
    //loop through data and push to array
    $.each(data, function(i,v){
       items.push('< th >'+v+'< /th >');
    });       
    //join array and append to table
    $('#sampleTable tbody').html(items.join(','));
    },
 error: function(err){
     console.log(err.responseText);
    }
});
}

//call populate every 10 secs (example only , you can change to how many    seconds you like)
setTimeout(function(){
  populate();
},10000);

data.php

$sql = 'SELECT id FROM usertbl';
$stmt = $hund->runQuery($sql);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);
echo json_encode($row);