Wednesday, 8 October 2014

JSON ,MySQL, PHP and Parse it with jQuery



getjson.php
<?php
$mysql_db_hostname = "localhost";
$mysql_db_user = "root";
$mysql_db_password = "";
$mysql_db_database = "practice";
$con = mysqli_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password,
$mysql_db_database);

if (!$con) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
$var = array();
$sql = "SELECT * FROM intellectuals_forum_members";
$result = mysqli_query($con, $sql);

while($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}
echo '{"users":'.json_encode($var).'}';
?>

showJson.html
<table class="mGrid" id="jsondata">
<thead>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Location</th>
</thead>
<tbody></tbody>
</table>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function(){
var url="getjson.php";
$("#jsondata tbody").html("");
$.getJSON(url,function(data){
$.each(data.users, function(i,user){
var newRow =
"<tr>"
+"<td>"+user.first_name+"</td>"
+"<td>"+user.last_name+"</td>"
+"<td>"+user.position+"</td>"
+"<td>"+user.company+"</td>"
+"<td>"+user.school+"</td>"
+"</tr>" ;
$(newRow).appendTo("#jsondata tbody");
});
});
});

</script>

0 comments:

Post a Comment