Alex Hunter
Alex Hunter

Reputation: 260

Properly Populate Html Table with JSON

I have this code to recieve json data from php

        $.getJSON("../controller/testController.php",{action:"one"}, function(data)
        {
            var datas = "";
        $.each(data, function(key,value)
        {
            datas += "<tr>";
                datas += "<td>"+value.data1+"</td>";
                datas += "<td>"+value.data2+"</td>";
                datas += "<td>"+value.data3+</td>";                     
            datas += "</tr>";
        })
            $(".tables").append(datas);
        })

This is the html

<table class="tables">
<thead>
<th>1</th>
<th>2</th>
<th>3</th>
</thead>
<tbody></tbody>
</table>

Why i cant select the data ? im checking it with this code. Is there a better way to do this? NOTE: With static data i can select it.

$('.tables tbody tr td').last().css("background","cyan");

UPDATE

Doing some coding i saw that if i put the "css" code inside the getJSON function, i can do the job. But doing it like this, ill cant make any manipulation of the data outside of the function (horrible coding). Any ideas to make this better?

Upvotes: 0

Views: 773

Answers (3)

Alex Hunter
Alex Hunter

Reputation: 260

This is the code to solve the problem.

$.getJSON("../controller/testController.php",{action:"one"}, function(data)
{
    var datas = "";
$.each(data, function(key,value)
{
    datas += "<tr>";
        datas += "<td>"+value.data1+"</td>";
        datas += "<td>"+value.data2+"</td>";
        datas += "<td>"+value.data3+</td>";                     
    datas += "</tr>";
})
    $(".tables").append(datas);
    $('.tables tbody tr td').last().css("background","cyan");
})

Putting the "css" code inside the getJSON

Upvotes: 0

Amit Kumar
Amit Kumar

Reputation: 5962

it's typing mistake.

instead of datas += "<td>"+value.data3</td>";

it should be datas += "<td>"+value.data3+"</td>";

Fiddle

Upvotes: 0

Tudor Danes
Tudor Danes

Reputation: 45

Maybe you have a typo in the line :
datas += "<td>"+value.data3</td>";

It should be :
datas += "<td>" + value.data3 + "</td>";

Upvotes: 1

Related Questions