KevMoe
KevMoe

Reputation: 443

Ajax api call table population

I am able to display api response in a single tag in an html table. However, I am trying to add another piece of the response into the table. I have hit the wall...

$.ajax({
type: 'GET',
url: "api query url",
auth: "user:password",
dataType: "json",
crossDomain: true,
success: function(data) {
var list = data.list;
$.each(list, function(i, item) {
var tr = $('<tr>').append($('<td>').text(item.name));

This is where I get stuck...

$('<tr>').append($('<td>').text(item.playerStatus)); 
$("#scalaapi").append(tr);
});
}
})

Here is a sample of the json response...

{
"list": [
    {
        "id": 30,
        "name": "Scala_Test Player",
        "playerStatus": "Active",
        "uuid": "f5672f69-be76-4057-8a46-68fa4ba9dda8",
        "previewPlayer": false,
        "enabled": true,
        "mac": "00-00-00-00-00-00",
        "type": "CHROMEBOX",
        "distributionServer": {
            "id": 2,
            "name": "Main",
            "driver": "IP_P2P"
        },
    }
}

And HTML...

<section class="reports">
<div id="output">
    <table id="scalaapi">
    <tbody>
    <tr><td></td><td></td></tr>
    </tbody>
    </table>
</div>
</section>

Upvotes: 1

Views: 548

Answers (1)

DevelopmentIsMyPassion
DevelopmentIsMyPassion

Reputation: 3591

Thats because you are initializing variable tr in loop. Hence its assigning new value to it and erasing old values. Declare it outside for each loop.

Please try below

$.each(val, function(i, item) {

       tr = $('<tr>').append('<td>' + (item.name) + '</td>' + 
                             '<td>' + (item.playerStatus) + '</td>');

       $("#scalaapi").append(tr);
  });

Here is link to JSBin

Upvotes: 1

Related Questions