How to load data using JSON/PHP using jQuery

I have seen a good amount of people wanting to lern how to load data on their website using jquery,JSON and PHP. I have been studying parsing JSON from PHP using AJAX to display it in the client side and jQuery had been a great help to me. Here is a very simple code in parsing JSON using jQuery that i made.

tablejsondata.php
This file makes the request to a php file and displays the returned data into a table.

<a href="#" id="loaduserdata">User Data</a>
<table id="userdata" border="1">
 <thead>
 <th>First Name</th>
 <th>Last Name</th>
 <th>Email Address</th>
 <th>City</th>
 </thead>
 <tbody></tbody>
</table>
<script>
$(document).ready(function(){
});
$("#loaduserdata").click(function(){
 $("#userdata tbody").html("");
 $.getJSON(
 "jsondata.php",
 function(data){
 $.each(data.userdata, 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>

jsondata.php
This is the file that contains the JSON data.
<?php
$json = '{
"userdata": [
 {
 "first":"Ciaran",
 "last":"Huber",
 "email":"elementum.purus@utdolordapibus.edu",
 "city":"Mayagüez"
 },
 {
 "first":"Lester",
 "last":"Watkins",
 "email":"orci.sem.eget@quamvelsapien.edu",
 "city":"Laguna Beach"
 },
 {
 "first":"Mannix",
 "last":"Gilmore",
 "email":"sed.sem.egestas@AliquamnislNulla.com",
 "city":"Minot"
 },
 {
 "first":"Nathaniel",
 "last":"Holland",
 "email":"a.odio@Donecnibh.org",
 "city":"San Angelo"
 },
 {
 "first":"Wylie",
 "last":"Drake",
 "email":"lobortis.nisi.nibh@Integer.edu",
 "city":"Roseville"
 },
 {
 "first":"Salvador",
 "last":"Alford",
 "email":"fringilla@adipiscing.edu",
 "city":"Vacaville"
 },
 {
 "first":"Kiara",
 "last":"Barton",
 "email":"fringilla.est.Mauris@utpellentesqueeget.ca",
 "city":"Johnson City"
 },
 {
 "first":"Moses",
 "last":"Miller",
 "email":"per.inceptos@aliquam.edu",
 "city":"Boulder Junction"
 },
 {
 "first":"Hillary",
 "last":"Serrano",
 "email":"elit.pretium.et@scelerisquesedsapien.com",
 "city":"Martinsburg"
 }
]
}';
echo $json;
?>

References and Guides:

http://docs.jquery.com/GetJSON

http://www.json.org/js.html
Download the latest jquery file.
Author: Jhoy Imperial

Advertisements

1 Comment

  1. Zimlu Tang Lee said,

    January 1, 2010 at 3:59 am

    Thanx, mait, now i coprihendo.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: