Jose Borges Jose Borges - 7 months ago 107
HTML Question

Get json data to html table

I have a json data from a mysql table that is queried from a php script. The json data is coming correctly like this:

{
"report": [{
"Mes": "Abril",
"Dia": "13",
"Local": "Lisboa",

}]
}


I tried this code to get the data into a html table. But since i'm a noob I don't know why isn't working.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

<script>
$.getJSON("http://ib.esy.es/_php/select_comissao1.php",
function (data) {
var tr = data.report
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].Mes + "</td>");
tr.append("<td>" + data[i].Dia + "</td>");
tr.append("<td>" + data[i].Local + "</td>");
$('.table1').append(tr);
}
});
</script>

<table class="table1">
<tr>
<th>Mes</th>
<th>Dia</th>
<th>Hora</th>
</tr>
</table>


Can someone help me?

Answer

Since you're saying the JSON is coming back, and assuming the object structure in the question is correct, a couple things stand out to me:

1) I don't understand why this line var tr = data.report is in the code. You're setting tr to your fetched data and then overwriting it with a jquery object in your loop.

2) The reason you're unable to get the data out of your JSON is that data is the root of your object. The data you're trying to write to the table is in the report property within the top-level data object. You can update your javascript to:

for (var i = 0; i < data.report.length; i++) {
  var tr = $('<tr/>');
  $(tr).append("<td>" + data.report[i].Mes + "</td>");
  $(tr).append("<td>" + data.report[i].Dia + "</td>");
  $(tr).append("<td>" + data.report[i].Local + "</td>");
  $('.table1').append(tr);
}

With the previous code, you were indexing into the data object which is not an array. This update makes sure the indexing is happening on the report property, which is an array.

Sample

$(document).ready(function() {
  // Using the JSON format from your question
  var data = {
    "report": [{
        "Mes": "Abril",
        "Dia": "13",
        "Local": "Lisboa",

    }]
  };

  // Loop through data.report instead of data
  for (var i = 0; i < data.report.length; i++) {
    var tr = $('<tr/>');
    
    // Indexing into data.report for each td element
    $(tr).append("<td>" + data.report[i].Mes + "</td>");
    $(tr).append("<td>" + data.report[i].Dia + "</td>");
    $(tr).append("<td>" + data.report[i].Local + "</td>");
    $('.table1').append(tr);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table1">
  <tr>
    <th>Mes</th>
    <th>Dia</th>
    <th>Hora</th>
  </tr>
</table>