Spewing JavaScript JSON with PHP

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!

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 JSON.org 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">
  <popup>
	<menuitem value="New" onclick="CreateNewDoc()" />
	<menuitem value="Open" onclick="OpenDoc()" />
	<menuitem value="Close" onclick="CloseDoc()" />
  </popup>
</menu>

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"
alert(menu.value); 

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…

<?php
// 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>");
	exit();
}

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

$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\" }";
		$counter++;
		
		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", "http://www.someurl.com", "pictureurl": "http://www.someurl.com/picture1.jpg", "rank": "1", "created": "2009-01-24 13:20:28"},
	 { "name": "property name 2", "url", "http://www.someurl.com", "pictureurl": "http://www.someurl.com/picture2.jpg", "rank": "2", "created": "2009-01-22 10:20:28"},
	 { "name": "property name 3", "url", "http://www.someurl.com", "pictureurl": "http://www.someurl.com/picture3.jpg", "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) {
		  
		  GetRequest.open("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
				displayProperties(properties);
			  }
		  }
		  
		  // Send out the request
		  GetRequest.send(null);
	  }
}

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 propertyList.property) {
		alert(propertyList.property[prop].name);
	}
}

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! 🙂

About The Author

Martyr2 is the founder of the Coders Lexicon and author of the new ebooks "The Programmers Idea Book" and "Diagnosing the Problem" . He has been a programmer for over 20 years. He works for a hot application development company in Vancouver Canada which service some of the biggest tech companies in the world. He has won numerous awards for his mentoring in software development and contributes regularly to several communities around the web. He is an expert in numerous languages including .NET, PHP, C/C++, Java and more.