enter image description hereI’m trying to populate the data in the html table with jquery and all columns get undefined error
Html:
<table id="example" class="table table-striped" style="width:100%">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>6</th>
<th>7</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
with the following instruction jquery
<script>
$(document).ready(function () {
// FETCHING DATA FROM JSON FILE
$.getJSON("http://localhost:8089/projectw/ServletJSON", function (data) {
var e= "";
// ITERATING THROUGH OBJECTS
$.each(data, function (key, value) {
//CONSTRUCTION OF ROWS HAVING
// DATA FROM JSON OBJECT
e += '<tr>';
e += '<td>' + value.ag + '</td>';
e += '<td>' + value.pa + '</td>';
e += '<td>' + value.ex + '</td>';
e += '<td>' + value.em + '</td>';
e += '<td>' + value.at + '</td>';
e += '<td>' + value.ct + '</td>';
e += '<td>' + value.num_ex + '</td>';
e += '</tr>';
});
//INSERTING ROWS INTO TABLE
$('#example').append(e);
});
});
</script>
json example in servlet:
{
"JsonTest": [
{
"ag": "RAX",
"pa": "pa 1",
"ex": "RXTT",
"em": "ME",
"at": 1,
"ct": 0,
"num_ex": "1"
},
{
"ag": "TOM",
"pa": "pa 2",
"ex": "TOCC",
"em": "MB",
"at": 0,
"ct": 0,
"num_ex": "2"
}
]
}
Observation If I order to display the json text
(
var req = new XMLHttpRequest();
req.open('GET', 'http://localhost:8089/projectw/ServletJSON', true);
req.send();
req.onload = function(){
var json=JSON.parse(req.responseText);
document.getElementsByClassName('message(class of table example)')[0].innerHTML = JSON.stringify(json)
),
I get success but to populate the table no.
how could i adjust this?
thank you all !
Expected lines to be filled with json values, no errors in console.
2
Answers
Thank you, I changed the information and got the correct result:
I believe it can help other dev because the forum contains more questions with JSON files and the few with the use of URL!
If you add a simple
console.log()
to your code to show whatkey
andvalue
are inside your loop, the problem is immediately obvious:The console shows:
And looking at your JSON object it is obvious – you have just 1 top level key,
JsonTest
, all your real data is nested under that. You want to be iterating overdata.JsonTest
, notdata
. Here’s a simplified working example with that error fixed:You really need to learn to do basic debugging – using your console is the first step in writing Javascript.
Note under SO guidelines I think this question should be considered a typo, and it is not likely to be useful to future visitors. I have voted to close as a typo.