Subscribe to Martyr2's Programming Underground        RSS Feed

Spewing Javascript JSON with PHP

Icon 7 Comments
There may be a time in the not so distant future where your employer may ask you do develop a web application which will hook up with a JSON data source. Perhaps you will be like "Uhhhhhh" and have a dumb look on your face. Have no worries, the underground is here to help! Lets use some PHP to generate some JSON code which we will fetch via AJAX and lastly have Javascript display the results via alerts on our page. We will not be looking to make this bullet proof but just to show you how one will go about doing it. Then at least you can shake your head and get to work before your boss has a cow. We will do it all right here on the Programming Underground!

<Oboes, violins, even a triangle playing sweet music... until skyhawk starts to vacuum the DIC chat room)

Lets start out by describing what JSON is. To help understand JSON you can remember back to the idea of XML. XML is used to mark up data and give it a structure. The problem with XML is that it could get a bit verbose for describing large objects. Having to always specify a beginning and end tag for each element can really add to the size of the data. Then on the other side you have to "unpackage" the data from the tags through parsing or creating a DOM document.

JSON on the other hand is a subset of Javascript which is very small and can quickly describe the structure of an object. It consists of nothing more than "name/value" pairs as well as object notation, array notation etc. A person can usually learn JSON in a day or two given they are fully aware of how Javascript works.

Using a function like eval(), Javascript can then quickly use this JSON data to build an object for functions to use. To show you what I mean I have taken an example from the website which shows you the XML version of a menu, as well as the JSON version of it.

The XML version looks like this...

<menu id="file" value="File">
	<menuitem value="New" onclick="CreateNewDoc()" />
	<menuitem value="Open" onclick="OpenDoc()" />
	<menuitem value="Close" onclick="CloseDoc()" />

Then the same thing represented as JSON...

{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
	"menuitem": [
	  {"value": "New", "onclick": "CreateNewDoc()"},
	  {"value": "Open", "onclick": "OpenDoc()"},
	  {"value": "Close", "onclick": "CloseDoc()"}

While this doesn't look like it is saving you much on typing, the saving here is actually going to be on the client side script that needs to process this code. In Javascript, you would take in the XML (through an AJAX call) and have to parse the code or stuff it in a DOM document and then traverse the DOM. However, with Javascript and JSON you can do something similar to...

// Now menu will be an object of the type (and structure) of whatever ajaxObj returned as JSON
var menu = eval('(' + ajaxObj.responseText + ')');

// Alert message to get access to value... Returns "File"

Nothing to it right?

Ok so our little example has a few pieces to it. The first piece is a PHP script which is going to read a database full of records and construct some JSON formatted code. You can do this generation using two different methods. It really depends on how much control you want and on your data's properties.

One method to do this is using a PHP function called json_encode() which takes in a PHP value and spits out the JSON representation of that value. The one little problem with this function though is that it doesn't work on "result" items returned from a database. So you would have to construct an object (perhaps fetch it as an object using mysql_fetch_object) and then use json_encode to spit out the JSON. The second method, which I quickly demonstrate, is simply echo'ing out the structure of an array of records. This will allow my Javascript to then iterate through our records and fetch the fields as properties.

Lets take a look at the PHP code real quick...

// Database connection details.... not shown

// Establish a MySql connection, otherwise it fails.
mysql_connect($DBhost,$DBuser,$DBpass) or die("Unable to connect to database");
if (! @mysql_select_db("$DBName") ) {
	echo("<P>Unable to locate the database at this time.</P>");

// Select our top 10 resort properties
$results = mysql_query("select * from top10");

$total = mysql_num_rows($results);

if ($total > 0) {
	// Start a JSON object called "property" which will be an array of resort properties from around the globe.
	echo '{ "property": [ ';
	$counter = 0;
	while ($item = mysql_fetch_object($results)) {
		echo "{ \"name\": \"$item->name\", \"url\": \"$item->url\", \"pictureurl\": \"$item->pictureurl\", \"rank\": \"$item->rank\", \"created\": \"$item->created\" }";
		if ($counter < $total) { echo ", "; }
	echo '] }';
else {
	// No resort properties were found, create empty array
	echo '{ "property": [] }';


As you can see from the code above I simply create a JSON array full of resort properties. Each resort is going to have a name, a URL to a page for more info, a URL to a picture to show, and a rank (since this is the top 10). I loop through the top 10 records and construct this array. The final result is something that looks like this...

{ "property": [
	 { "name": "property name 1", "url", "", "pictureurl": "", "rank": "1", "created": "2009-01-24 13:20:28"},
	 { "name": "property name 2", "url", "", "pictureurl": "", "rank": "2", "created": "2009-01-22 10:20:28"},
	 { "name": "property name 3", "url", "", "pictureurl": "", "rank": "3", "created": "2009-01-21 08:23:29"}

The square brackets above show the beginning and ending of the JSON array. Each element of that array is enclosed in curly braces themselves.

The second part we are going to need is some Javascript to call this PHP page now. So lets create a simple AJAX setup for our testing purposes....

// Create an XMLHttpRequest objec to facilitate AJAX communication
function getObject() {
	 var XMLRequestObject = false;

	 if (window.XMLHttpRequest) {
		XMLRequestObject = new XMLHttpRequest();
	 else if (window.ActiveXObject) {
		XMLRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
	 return XMLRequestObject;

// GetData fetches the requested page and parses return JSON from a "trusted" source.
function getData(sourcestring) {
	  GetRequest = getObject();

	  if (GetRequest) {"GET",sourcestring);	
		  GetRequest.onreadystatechange = function() {
			  // Receive the response and check if it is ok
			  if ((GetRequest.readyState == 4) && (GetRequest.status == 200)) {
				  // Evaluate the JSON that we are getting back from our PHP page and make it an object called "properties"
				  var properties = eval('(' + GetRequest.responseText + ')');
				// Now display the properties
		  // Send out the request

So here we have a standard AJAX call where one function constructs an object and the second sends out the request to our PHP page (which is passed in as "sourcestring"). Upon receiving the data, it will construct an object we call "properties" and then passes that object off to a function for displaying.

Now keep in mind that if you are going to run this code locally on your computer you may get some security warnings or, in the case of Firefox, flat out deny you the call for security reasons. One way to get around it is to toss it up on a web server and make a call to the script which is on the same machine and domain. That way the browser will trust the source.

Also keep in mind that eval() will evaluate any Javascript code coming into it, so be sure that the source is trusted. In this case since we control the server we can guarantee that the source is something we trust.

The JSON served up by our PHP page is going to come in and be evaluated using the page's Javascript eval() function. Here Javascript will build our object using the JSON and set it to a variable called "properties" (properties as in resort properties). Then it tosses the new object off to a display function for us to display the results anyway we like.

Below is a simple function which will loop through the object's array of properties and display the name field...

// Using a for each loop we loop through the property array and alert the user to the name of each resort fetched.
function displayProperties(propertyList) {
	for (var prop in {

If you put these three pieces together, the PHP creating the JSON, the AJAX to fetch the JSON from the PHP page, and the Javascript to evaluate and display the parsed JSON, you will have a complete solution for fetching and displaying JSON data. Feel free to use this code where you like. You will need to make quite a bit of changes to it for use in different situations but it shouldn't take you too long. This code is nice for little gadgets on pages, Google Gadgets, or you can take the first part and start your own JSON API to your database.

Hope you enjoyed the reading and that you didn't get too overwhelmed by the code. Thanks for reading! :)

If you want more blog entries like this, check out the official blog over on The Coders Lexicon. There you will find more code, more guides and more resources for programmers of all skill levels!

7 Comments On This Entry

Page 1 of 1


25 January 2009 - 10:08 AM
Good G*d, I think I'am jealous, I am green with envy, I don't think I've ever be truly envious in my entire life, until now.
Until 2yrs ago, I did not know what a computer looked like, if you had said url to me I would probably have slapped you for being rude, I have found my passion, sadly, to late in life for it to really matter.
I am quiet ill honestly, I wish I could know 1/10000000 th, of what u know.
I wrote an article on ajax, which is waiting managements approval, I hope they never approve it because against this it is wholly inadequate, I think I'am crying now sob.. sob, keep-up the stunning work.


25 January 2009 - 10:20 AM
sorry, my phone is over posting again, please don't let jjsaw5, catch me.


25 January 2009 - 10:44 AM
Don't worry, I took care of the extra posts... you are safe. Thanks for the compliment (even though I am not sure I deserve such an over the top one). I hoped it would help someone out.



25 January 2009 - 08:27 PM
I love it, i always wondered what JSON was and now i know (yes i know i should of used google but i never remembered to). Nice tutorial and i have definatly learnt a lont


29 January 2009 - 08:22 PM
thanks very much!

very useful :^:

you could have used it:

function displayProperties(propertyList) {{alert(});

other thing: there's no need of double quote.
echo "{ \"name\": \"$item->name\", \"url\": \"$item->url\", \"pictureurl\": \"$item->pictureurl\", \"rank\": \"$item->rank\", \"created\": \"$item->created\" }";

could be:
echo "{ name: \"$item->name\", url: \"$item->url\", pictureurl: \"$item->pictureurl\", rank: \"$item->rank\", created: \"$item->created\" }";


30 January 2009 - 04:33 AM
other think that would be nice:

use this:
++$counter < $total ? print ', ' : print '';

instead of:
if ($counter < $total) { echo ", "; }


30 January 2009 - 02:50 PM

tivrfoa, on 29 Jan, 2009 - 07:22 PM, said:

thanks very much!

very useful :^:

you could have used it:

function displayProperties(propertyList) {{alert(});

other thing: there's no need of double quote.
echo "{ \"name\": \"$item->name\", \"url\": \"$item->url\", \"pictureurl\": \"$item->pictureurl\", \"rank\": \"$item->rank\", \"created\": \"$item->created\" }";

could be:
echo "{ name: \"$item->name\", url: \"$item->url\", pictureurl: \"$item->pictureurl\", rank: \"$item->rank\", created: \"$item->created\" }";

Actually it is strongly advised to use the double quotes around the property names as well. Leaving them off is just going to force an implicit cast to string anyways which you never really want to do in programming. The specification for JSON shows that all string property names should also be in double quotes.

But thanks for the forEach tip. Unfortunately that method doesn't appear until Javascript 1.6 so it may break in some of the older browsers like IE 6 and so for now using the actual for each style will be cross browser compliant.

Glad you found the entry to your liking. :)
Page 1 of 1

October 2020

18192021 22 2324

Recent Entries

Recent Comments

Search My Blog

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)