Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

pickab00's avatar

Adding table tr and td using JQuery for each result

So I have an ajax with json results which shows about 3 results at the moment. And I want to be able to populate the tbody with tr depending on the number of the results. And of course populating the td with the actual results per each tr. Hope I am making sense here. Here is what I am using to loop through my results.

if(res.length) {


            $.each(res, function(i, element){

                var id=element.id;
                var department=element.department;

                $('#custom-table-body tr').each(function() {

                });


                console.log(department);

            });

        }

Console logging department shows 3 results. So that basically means that the table to create 3 tr. And Inside each of those tr, there will be td for their id and department.

Example for expected result:

<tr>
    <td>1</td>
    <td>IT</td>
    <td>John</td>
    <td>Male</td>
    <td>America</td>
    <td>48484</td>
    <td>active</td>
</tr>

<tr>
    <td>2</td>
    <td>IT</td>
    <td>Smith</td>
    <td>Male</td>
    <td>America</td>
    <td>3232</td>
    <td>active</td>
</tr>

<tr>
    <td>3</td>
    <td>IT</td>
    <td>Wick</td>
    <td>Male</td>
    <td>America</td>
    <td>3333</td>
    <td>active</td>
</tr>

I do not know where to even begin with this.

0 likes
4 replies
pickab00's avatar

@SNAPEY - This works great. But here is the issue. Assuming that I want to refresh this every 3 seconds (3000ms), and I am using the old setTimeOut method to refresh the function. The problem with doing so is that this keeps on repeating every 3 seconds rather than replacing the existing data.

Snapey's avatar

You either have to rip out the added rows or give each row an id and then just update that row

1 like
pickab00's avatar

@SNAPEY - Thanks! Though I just figured that append is not the best approach. Nor is using timeout to refresh it 3 seconds with append. Then again, using html() is not meant for arrays. Got it working with append. Clearing old and appending works. "Reappending" I guess. Thanks again

Please or to participate in this conversation.