June 28, 2012
add data dynamically from JSON array to HTML table using JQuery
Question by nag
php file:
<?php
mysql_connect("127.0.0.1");
mysql_select_db("test");
$sql=mysql_query("select first,last,email,city from userdata");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
json output:
[{"first":"nag","last":"ch","email":"nag@gmail.com","city":"guntur"},{"first":"hari","last":"ch","email":"hari@gmail.com","city":"guntur"}]
html code:
<script>
$(document).show(function(){
});
$("#userdata tbody").html("");
$.getJSON("http://127.0.0.1/reg/userdata.php",function(data){
$.each(data,function(i,user){
var tblRow =
"<tr>"
+"<td>"+user.first+"</td>"
+"<td>"+user.last+"</td>"
+"<td>"+user.email+"</td>"
+"<td>"+user.city+"</td>"
+"</tr>"
$(tblRow).appendTo("#userdata tbody");
});
}
);
</script>
i was displayed data from database using php in JSON format..i want to insert this data into table format in html page, i created table in html also..i tried using above script but it didn’t fetch any data..plz help me plz..
Answer by Starx
Your PHP is printing the array in an incremented format.
Make the following changes:
print(json_encode($row));
Next, there is no userdata in the output, so just use data
.