AJAX, Asyncronous Javascript and XML. A phrase we're all too familiar with these days. I was pointed down a road to JSON land from a fine developer named Owen. In JSON land things are serialized for you as native Javascript objects and I might not turn back. I've been playing around today with JSON "AJAX" transactions today and I must say it was so much faster to develop than traditional XML based messaging from server to client. I've never been a big fan of bloated AJAX frameworks like SAJAX or JPSPAN which tries to map PHP to JAVASCRIPT. Personally I think its a waste of parsing overhead if you're a capable developer.

If you run a high performance, heavy load server you're really looking to maximize every byte of data you can to keep your bandwidth costs down. XML can become beefy at times, consuming more bandwidth than really needed for most applications. Being able to take a php array and return it as a serialized native Javascript object can be quite powerful and easy! I chose to start out with a pear class called JSON.php http://mike.teczno.com/JSON/JSON.phps

With one method call you can serialize a native php type into a native javascript type, then eval that code and use it right away in your javascript code.

$JSON = new Services_JSON();

$my_arr = array('hey', 'dude', 'whats', 'up');

echo $JSON->encode($my_arr);

which will return to the client a string of:


which when properly eval'd in javascript becomes a native JS array. Which can be iterated through right away without having to be loaded into an XML dom structure.

Lets take a look at a very simple RSS Title fetcher written in PHP5 using JSON as the structure to be passed from client to server. You can find the class_xmlhttp.js class here: http://www.litfuel.net/tutorials/js_errors/class_xmlhttp.js

Here is a working example: http://meetbos.com/temp/ajaj/ajaj.html

sorry its slow but the server is a dog lately.



Click me for yahoo RSS

Click me for DIGG RSS



$JSON = new Services_JSON();

if($_POST['feed'] === 'yahoo') {
$url = 'http://rss.news.yahoo.com/rss/topstories';
} else {
$url = 'http://digg.com/rss/index.xml';
// grab the contents of the rss feed

$rss_file = file_get_contents($url);

// load up our simple xml object
if(!$feed = simplexml_load_string($rss_file))
// you would send an error back up to the client for processing
die("Cannot load RSS Feed. This application supports RSS 1.0 and 2.0");

//title of the feed
$rss['title'] = (string)$feed->channel->title;

// check for RSS Version
$items = ($feed['version'] != '') ? $feed->channel->item : $feed->item;

foreach($items as $item)
$rss['items'][] = (string)$item->title;
echo $JSON->encode($rss);

and here is what that multidimensional array looks like when it returns back to the client

{"title":"Yahoo! News: Top Stories","items":["Bush, Merkel Take United Stance on Iran (AP)","Gonzales to Testify on Domestic Spying (AP)","Sharon Fails to Come Out of Coma (AP)","Hostile Fire Cited in U.S. Chopper Crash (AP)","Overwhelming odds against survival (USATODAY.com)","SWAT Team Shoots Armed Fla. 8th-Grader (AP)","Alito Hearings Close, Confirmation Likely (AP)","Alaska Volcano Erupts Third Time in a Week (AP)","Tyco to Split Into 3 Cos. at Cost of $1B (AP)","Angelina Jolie and Brad Pitt Visit Haiti (AP)","Iran threatens to curb inspections (Reuters)","Gonzales to testify on domestic spying program (Reuters)","Specter says will vote for Alito (Reuters)","US helicopter downed in Iraq, two dead (Reuters)","Sharon still in coma, doctors concerned (Reuters)","Defiant Iran threatens to halt nuclear cooperation (AFP)","Sharon's condition 'very worrying' on ninth day of coma (AFP)","Bush says nuclear-armed Iran a threat to the world (AFP)","Chilean women ready to defy macho politics (AFP)","Saudi shrugs off responsibility for deadly stampede (AFP)"]}

which when eval'd gets turned into a nice little JS Object which in Venkman's debugger looks like this:

where the "items" element is an array of the news feeds. Again, this is a super simple example of JSON but it should help to show you how much faster development can go when you don't have to parse through XML nodes and can have native javascript objects right from your php output. This simple fact would allow you to reuse simple applications you already have or functions you already have with just a FACADE pattern wrapper to serialize the data.

If you really wanna beef up the speed and can roll your own extensions I suggest looking at this JSON EXT for PHP
http://www.aurore.net/projects/php-json/ which claims to be 85 times faster than the PHP script version I used above to serialize the data.

So a couple highlight benefits to JSON over XML or Text is:

*Ability to reuse your old functions/methods with just a wrapper around to serialize the returned data
*Ability to fetch JSON data from other domains which you can't do with xmlhttp alone
*Lower bandwidth
*Faster rendering times
*Less Code

Ready for More?

Follow Me @jimplush