Reputation: 441
I'm having issues building an html table with a JSON object that I've already got generated by a php page.
I'm building my JSON object from a spreadsheet where it includes: Fname, Lname, Ext, Rm.
My json.php webpage gives me this result:
[{"fName":"John","lName":"Doe","Ext":"#666","Rm":"C3","id":0},{"fName":"Abraham","lName":"Lincoln","Ext":"#917","Rm":"C1","id":1}]
So now I'm trying to build an html page filling a table with this data using jquery. Here's what I've got for my index.html:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript">
</script>
</head>
<body>
<div id="stuff"
<table id="userdata" border="1">
<thead>
<th>First Name</th>
<th>Last Name</th>
<th>Ext</th>
<th>Room</th>
</thead>
<tbody></tbody>
</table>
</div>
<script>
$(document).ready(function(){
$("#userdata tbody").html("");
$.getJSON("json.php", function(data){
$.each(data.members, function(i,user){
var tblRow =
"<tr>"
+"<td>"+user.fName+"</td>"
+"<td>"+user.lName+"</td>"
+"<td>"+user.Ext+"</td>"
+"<td>"+user.Rm+"</td>"
+"</tr>"
$(tblRow).appendTo("#userdata tbody");
});
}
);
});
</script>
EDIT: Found my solution with the following code:
<?php
$json = file_get_contents('collab.json.php');
$data = json_decode($json,true);
echo '<table>';
echo '<tr><th>Username</th><th>Period</th><th>Room</th><th>Next?</th></tr>';
$n = 0;
foreach ($data as $key => $jsons) {
foreach ($jsons as $key => $value) {
echo '<tr>';
echo '<td>'.$data[$n]['username'].'</td>';
echo '<td>'.$data[$n]['period'].'</td>';
echo '<td>'.$data[$n]['Rm'].'</td>';
echo '<td>'.$data[$n]['next'].'</td>';
echo '</tr>';
$n++;
}
}
echo '</table>';
?>
</html>
Upvotes: 3
Views: 5490
Reputation: 2742
usually in these situations, I add the items to an array and then join and append the array. so for example, in your each.
tblRow = [
'<tr>',
'<td>' + user.fName + '</td>',
'<td>' + user.lName + '</td>',
'<td>' + user.Ext + '</td>',
'<td>' + user.Rm + '</td>',
'</tr>',
].join('\n');
myArray.push(tblRow);
myArray being an empty array outside of your loop, and then after the loop append the array content to your table.
Hope this helps!
Upvotes: 0
Reputation: 4616
Assuming that the json you provided is the only output from your json.php
you have to slightly change this line:
$.each(data.members, function(i,user){
To this:
$.each(data, function(i,user){
Upvotes: 1