Parsing JSON Data from PHP Using jQuery

Posted on Updated on


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.

<html>
<head>
	<title>Parsing JSON From PHP Using jQuery</title>
	<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript">
	</script>
</head>
<body>
	<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>
</body>
</html>

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.

40 thoughts on “Parsing JSON Data from PHP Using jQuery

    Liaam said:
    October 6, 2008 at 4:14 AM

    Hi, I loost all day working on this problem. I found your example and I found that also your code, doesn’t work on IE.

    Maybe U have already solved this problem, if yes, can U tell me how?!
    Thanks!

    jhOy imPeRiaL responded:
    October 6, 2008 at 7:10 AM

    hi Liaam,

    i’ve re-tested it again but it’s working.

    is this your email? i’ll try to send you the files.
    🙂 jhoy

    Ervin Ter said:
    November 13, 2008 at 12:27 AM

    Thanks a lot especially on json part.

    jhOy imPeRiaL responded:
    November 13, 2008 at 10:17 AM

    @Ervin Ter,

    you’re very much welcome. i’m glad you liked this post

    jhoy

    Mattias said:
    January 15, 2009 at 3:31 PM

    if you wanna parse a php array instead you use
    the json_encode($php_array) function.

    If you want to parse a json object in php you do the opposite: json_decode($json_object[, true || false])

    if you want to parse it into an object you leave out the second parameter or set it to false.
    if you want an associative array you set second parameter to true.

    alex said:
    January 28, 2009 at 5:33 AM

    Lot’s of thanks for your help from catalonia!!!!

    Mark said:
    February 10, 2009 at 8:10 PM

    Found this really helpful, thanks for posting.

    shoorace said:
    March 31, 2009 at 12:22 PM

    Hi, how can I make it working on cross-domain like below?
    “http://otherdomain/jsondata.php”

    It gives me error-
    Access to restricted URI denied” code: “1012

    jhOy imPeRiaL responded:
    March 31, 2009 at 2:48 PM
    scvinodkumar said:
    July 1, 2009 at 6:09 PM

    Hi,

    could you please send me the updated code to my mail id?

    I copied your code and run it in my local system. Its working fine in firefox but not in IE7.

    Could you please whats needs to change in the above code

    jhOy imPeRiaL responded:
    July 1, 2009 at 7:38 PM

    hi scvinodkumar,

    what i just did was to clear the cache and it worked. just a couple times of clearing though.

    HTH
    jhoy

    […] the article here: Parsing JSON Data from PHP Using jQuery « jhoy imperial and the web Share and […]

    suresh said:
    February 26, 2010 at 7:54 PM

    Guys no need to panic, that its not working in IE7. just add ‘var’ to $json = ‘{ now it becomes

    var=$json = ‘{}’;

    It works like a charm

    Markus said:
    May 12, 2010 at 4:45 PM

    thanks mate
    you’ve saved me the day

    Anes P.A said:
    November 9, 2010 at 6:21 PM

    Hi friend,
    Thanks for your grate Stuff, friend I am really confused
    how to parse the json data, pls help my json data is:

    {“access_servers”:[{“id”:”2″,”servername”:”anes.admod.net”,”ip_address”:”10.10.3.28″,”ssh_port”:”22″,”description”:””,”enable_ssh”:”Y”,”cp_id”:”0″,”dc_id”:”0″,”servergroup_id”:”1″,”groupname”:”test”},{“id”:”1″,”servername”:”neseema.admod.net”,”ip_address”:”10.10.3.12″,”ssh_port”:”22″,”description”:””,”enable_ssh”:”Y”,”cp_id”:”0″,”dc_id”:”0″,”servergroup_id”:”1″,”groupname”:”test”}],”rows_server”:2,”group”:[{“id”:”1″,”name”:”test”,”description”:””,”created”:null,”modified”:”2010-11-08 12:00:43″}],”user”:{“id”:”1″,”firstname”:”Ezeelogin”,”created”:”0000-00-00 00:00:00″,”lastname”:”Administrator”,”email”:””,”usergroup_id”:”1″,”status”:”1″,”ip_enable”:”N”,”priv”:”0″},”server_group_name”:{“1″:”test”},”userarray”:{“id”:”1″,”firstname”:”Ezeelogin”,”created”:”0000-00-00 00:00:00″,”lastname”:”Administrator”,”email”:””,”usergroup_id”:”1″,”status”:”1″,”ip_enable”:”N”,”priv”:”0″},”usergroupid”:”1″,”offset”:0,”server_details”:”N”,”sshport”:”22″,”sshuser”:”root”,”pagelinks”:””,”totrows”:”2″,”limitvalue”:”10″,”current”:”server”,”sort_by”:”servername”,”sort_order”:”ASC”,”controlpanels”:{“1″:”Cpanel\/WHM”,”2″:”Plesk”,”3″:”Webmin”,”4″:”Webmin secure”},”datacenters”:[]}

    I am waiting your one’s help, reply me at : anes(dot)pa@gmail(dot)com

    Thankfully
    Anes

    Anes P.A said:
    November 10, 2010 at 10:58 AM

    Hi Friends,
    Thanks I got the solution, by using data(which is the return from server) , then take it as
    data.sort_order

    ok thanks

    bye Anes

    jhOy imPeRiaL responded:
    November 15, 2010 at 5:49 AM

    hi anes,

    glad your problem was solved.

    Jhoy

    Stefan said:
    December 6, 2010 at 4:48 PM

    hi Anes,

    could you give your complete solution (for noobies as me)
    thanks

    Baltej Singh said:
    March 30, 2011 at 9:26 AM

    Nice… Exactly what i was looking for!

    dayat said:
    April 7, 2011 at 4:15 PM

    I’ve got nothing, whats wrong ?

    I am using Netbeans.

    Gilbert said:
    April 26, 2011 at 8:33 AM

    Hi,
    I saw that you are a PHP web developer.
    Are you doing freelance work? Mag iinquire sana ako sa website.
    How can I talk to you? Please email me regarding sa website.
    Thanks I’ll wait for your reply.

    ali089 said:
    July 9, 2011 at 8:26 AM

    Hi,
    interesting post .. but I tried to make it run it didn’t run with me. can you please tell me what I need to make it run ?
    and send me the steps please ? what I need to download ?

    Thanks I am waiting for you reply ?

    ali089 said:
    July 9, 2011 at 11:55 AM

    hi I like post,
    I am actually working on this problem.
    I tried to run yours but it doesn’t work with me can you tell me how you run and what I should to install in my machine to make it run ??

    I am wating for reply . thanks

    Carl said:
    July 20, 2011 at 2:38 PM

    For weeks I’v trying to get this to work. Prior coming to your blog I’ve had no success. I’m having a difficulty understanding jquery – mainly the syntax. The brackets and braces confuse me and the plain english doesn’t help. You code is formatted so well I can understand where everying goes and how the code works with each other.

    Many thanks!

    Alberto Valero Ortega said:
    September 6, 2011 at 1:06 PM

    Hello,
    It works fine, but i cant send an url parameter to $.getJSON, when i try to get the parameter value on php i cant the data on the client, im trying the next:
    var urlJSON = “some.php?param=value”;
    $.getJSON(
    urlJSON,
    function(data){}
    //some.php
    domainName= $_POST[‘domain’];

    what i’m doing wrong? thx

    […] browsing the internet, the best tutorial I found on JSON was here – https://jhoyimperial.wordpress.com/2008/07/28/parsing-json-data-from-php-using-jquery/. It’s simple, straight forward, and shows a nice working […]

    falkon303Ben Althauser said:
    September 17, 2011 at 9:59 AM

    Very nice write-up! I wrote a post myself on using your example and modifying it to allow JSON to parse AJAX $_GET data as a function. This way, all requesting can be done PHP side. It seems to be working wonderfully. There are of course security measures to think about, but I think it could be bundled into a very slick JQuery Library. 🙂 I am excited about the idea of using php functions in collaboration with this. – http://falkon303.wordpress.com/2011/09/17/tripping-the-json-dynamic-using-ajax-to-send-json-javascript-functions/

    Mark Paul de la Vega said:
    September 20, 2011 at 5:42 PM

    Thank you for this one! I am also a Filipino like you…. and I was amazed… a girl programmer! hahah

    Zonasocial.com said:
    October 9, 2011 at 2:35 PM

    Add cache: false to not cache php file:

    $(document).ready(function(){
    $.ajaxSetup ({ cache: false})
    });

    Zonasocial.com said:
    October 9, 2011 at 3:36 PM

    For who want to use “json_encode” php to array mysql querys here is the solution:

    array(
    array(“first”=>”Ciran”,
    “last”=>”Huber”,
    “email”=>”elementum.purus@utdolor.edu”,
    “city”=>”Mayagüez”
    ),
    array(“first”=>”Lesterrrr”,
    “last”=>”Watkins”,
    “email”=>”orci.sem.eget@quamve.edu”,
    “city”=>”Laguna Beach”
    ),
    array(“first”=>”Mannix”,
    “last”=>”Gilmore”,
    “email”=>”sed.sem.egestas@Aliq.com”,
    “city”=>”Minot”
    )
    )
    );

    echo json_encode($phparray);
    ?>

    Zonasocial.com said:
    October 9, 2011 at 3:42 PM

    AGAIN Past Example was incomplete:

    For who want to use “json_encode” php to array mysql querys here is the solution:

    $arraytojson =
    array(“userdata”=>
    array(
    array(“first”=>”Ciran”,
    “last”=>”Huber”,
    “email”=>”elementum.purus@utdolor.edu”,
    “city”=>”Mayagüez”
    ),
    array(“first”=>”Lesterrrr”,
    “last”=>”Watkins”,
    “email”=>”orci.sem.eget@quamve.edu”,
    “city”=>”Laguna Beach”
    ),
    array(“first”=>”Mannix”,
    “last”=>”Gilmore”,
    “email”=>”sed.sem.egestas@Aliq.com”,
    “city”=>”Minot”
    )
    )
    );
    echo json_encode($arraytojson);

    Brian Walker said:
    November 10, 2011 at 6:22 AM

    Awesome tutorial THANKS…
    I have a JSON data set below (yes it is for the Scouts):
    I need to build dynamic forms using the data, and I can’t figure out how to work with it. I need to get the length of each level, for example (badges.length) should give me 4 (Webelos, Scout, Scouters, and Den Leaders). I need to build radio buttons for the four groups, select one, say Webelos, then I need the length of Webelos,length 6, (800, 9:30, 1100, 1230, 1330 and 2100) then I need to build a form and have six select list with options taken from the next level of the data (for the 800 select list the options would be “Outdoorsman, Traveler, Geologist and Readyman” I also need to keep the length of the class (they are all 1.30 hours in this case but in the Scout data they have 4 hour classes, so if they selected a 4 hour class at 8, the next four hours of selects would grey out).

    Basically I am dynamically creating the whole registration web site. But I have to figure out how to get the lengths and contend out of the JSON file first. All the examples I see start with arrays, not objects in the second level… Help, and Thanks in advance! I gave you 5 stars on the tutorial, it works great!

    Brian Walker said:
    November 10, 2011 at 6:23 AM

    $json = ‘{
    “badges”:{
    “Webelo”:{
    “800”:{
    “Outdoorsman”:130,
    “Traveler”:130,
    “Geologist”:130,
    “Readyman”:130
    },
    “930”:{
    “Outdoorsman”:130,
    “Traveler”:130,
    “Geologist”:130,
    “Readyman”:130
    },
    “1100”:{
    “Outdoorsman”:130,
    “Traveler”:130,
    “Geologist”:130,
    “Readyman”:130
    },
    “1230”:{
    “Lunch”:100
    },
    “1330”:{
    “Readyman”:130,
    “Scientist”:130,
    “Free Time Activities”:130
    },
    “2100”:{
    “Willbring3DGlasses”:200,
    “Buy $2 3D glasses”:200
    }
    },
    “Scout”:{
    “800”:{
    “NASA Interactive”:100,
    “Robotics”:400,
    “Metalwork”:400
    },
    “900”:{
    “SpaceExploration”:300,
    “Aviation”:300,
    “Electronics”:300
    },
    “1000”:{
    “Scholarship”:100
    },
    “1100”:{
    “Citizenship in the World”:200,
    “Pulp & Paper”:200,
    “Disabilities Awareness”:200,
    “Lunch”:100
    },
    “1200”:{
    “Robotics”:400,
    “Energy”:200,
    “Lunch”:100
    },
    “1300”:{
    “Aviation”:300,
    “Electronis”:300,
    “Soil & Water Concervation”:300
    },
    “1400”:{
    “Pulp & Paper”:200,
    “Emergency Preparedness”:200
    },
    “1500”:{
    “Scholarship”:100
    },
    “1600”:{
    “Duct Tape”:100
    },
    “1700”:{
    “Truck Transportation”:200
    },
    “2100”:{
    “Will bring 3D Glasses”:200,
    “Buy $2 3D glasses”:200
    }
    },
    “Scouters”:{
    “2100”:{
    “Will bring 3D Glasses”:200,
    “Buy $2 3D glasses”:200
    }
    },
    “Den Leaders”:{
    “2100”:{
    “Will bring 3D Glasses”:200,
    “Buy $2 3D glasses”:200
    }
    }
    }
    }’;
    echo $json;

    kirthi said:
    January 6, 2012 at 2:04 AM

    jhOy imPeRiaL:

    can you send me the source code.. its not working for me.

    thanks in advance.

    Titis Kaifa said:
    February 2, 2012 at 7:19 PM

    Thanks . It’s work🙂

    Prakshep said:
    February 13, 2012 at 8:51 PM

    Hi all,

    $.getJSON function not firing in my webpae.
    here i will put the code :
    function getData(keyid) {
    $.getJSON(“http://localhost/data.php?keyid=” + keyid, function(data){
    $.each(data.results, function(i,result){
    .getCmp(“dataForm”).getForm().setValues({
    Powner: result.one,
    sno: result.two,
    village: result.three
    });
    });
    }
    Json data formate is:

    {“results”:[
    {“one”:”16″,
    “two”:”17″,
    “three”:”18″}]}

    In fact, the getData() function called but $.getJSON not call
    what is wrong with this code? pl. help me.

    Thanks

    Kapil Dev said:
    March 6, 2012 at 7:15 PM

    Thanks………

    sasi said:
    April 10, 2012 at 7:56 PM

    good work sir..
    Thank you

    14 jQuery Plugin For JSON said:
    October 4, 2012 at 8:06 PM

    […] This allows you to easily remove data from other sites and services on your own site. Learn to use this feature makes it easy to integrate a variety of services in your sites, making them richer and more interesting to your visitors. Source […]

    Leon Revill said:
    December 5, 2012 at 6:47 PM

    I created an in-depth PHP jQuery search tutorial which looks at JSON objects being passed between PHP and Query. Take a look I hope it helps someone! PHP jQuery Search.🙂

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