user5405873 user5405873 - 23 days ago 9
Ajax Question

i have continuous ajax call how can i construct a table with the returned data

i'm in a situation where i get data from

server_side
in every
1 minute
my

question is how can i construct a table with the returned data?

i'm trying something like this but not working.

<div id="table"></div> <!-- my html -->


var something = "abc";

function callEveryMin(){
$.ajax({
url:"test.php",
type:"POST",
dataType:"json",
data:{something:something},
async: false,
success: function(data){
var array = data.list;
console.log(array);
var table = '<table><tr><th> list value </th></tr>';
for(var i = 0; i<array.length;i++)
{
table += '<tr><td>'+array[i]+'</td></tr>';
}
table +='</table>';
$('#table').append(table);

}
});

}

// call the above function every minute

setTimeout(callEveryMin,60000);


my php will be like this (test.php)

echo json_encode(array("list" => ['a','b','c'])); // first run


and on second run like this

echo json_encode(array("list" => ['e','f','g'])); // second run


so on ......

my question is how can i append new
<td>...</td>
on every
sucessive ajax call


please help me thanks in advance

Answer

Try this

<div id="table"></div>  <!-- my html -->


    var something = "abc";

function callEveryMin(){
         $.ajax({           
                url:"test.php",
               type:"POST",
               dataType:"json",
               data:{something:something},
               async: false,
               success: function(data){
                   var array = data.list;
                   console.log(array);
                   var table = ($('#table').html() == '')?'<table><tr><th> list value </th> </tr>':'';//if #table don't have a data inside it then add this else add empty
                   for(var i = 0; i<array.length;i++)
                   {
                        table += '<tr><td>'+array[i]+' </td></tr> ';
                   }
                   table +=($('#table').html() == '')?'</table>':'';//if #table don't have a data inside it then add this else add empty
                   $('#table').append(table);

              }
          });

}

// call the above function every minute

setTimeout(callEveryMin,60000);