New AJAX ancronym? Move Over XML...JSON puts the J in AJAJ

January 13, 2006

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.

  1.  
  2. <?php
  3. require_once('JSON.php');
  4. $JSON = new Services_JSON();
  5.  
  6. $my_arr = array('hey', 'dude', 'whats', 'up');
  7.  
  8. echo $JSON->encode($my_arr);
  9. ?>


which will return to the client a string of:

["hey","dude","whats","up"]

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.

index.html
  1.  
  2. <HTML>
  3. <HEAD>
  4.  
  5. <SCRIPT SRC="api/class_xmlhttp.js"></SCRIPT>
  6. <SCRIPT>
  7. var s = new XMLHTTP("api/server.php?");
  8. function showStuff(rss_feed)
  9. {
  10. s.call('feed='+rss_feed, processReqChange);
  11. }
  12.  
  13. function processReqChange()
  14. {
  15. // only if req shows "complete"
  16. if (s.req.readyState == 4) {
  17. // only if "OK"
  18. if (s.req.status == 200) {
  19. var myObject = eval( '(' + s.req.responseText + ')' );
  20. processResults(myObject);
  21. }
  22. }
  23. }
  24.  
  25. function processResults(myObject)
  26. {
  27. // REMOVE OLD NODES
  28. var results = document.getElementById('results');
  29. while(results.hasChildNodes()) {results.removeChild(results.firstChild);}
  30. // CLEAR TITLE
  31. var title_text = document.getElementById('title');
  32. while(title_text.hasChildNodes()) {title_text.removeChild(title_text.firstChild);}
  33. // ADD TITLE
  34. var title_text = document.createTextNode(myObject.title);
  35. document.getElementById('title').appendChild(title_text);
  36. // lets iterate through my new objects and add all those new items to my UL list I have waiting
  37. var len = myObject.items.length;
  38. for(var i=0; i < len; i++)
  39. {
  40. var li = document.createElement('li');
  41. var li_text = document.createTextNode(myObject.items[i]);
  42. li.appendChild(li_text);
  43. document.getElementById('results').appendChild(li);
  44. }
  45. }
  46. </SCRIPT>
  47. </HEAD>
  48. <BODY>
  49. AJAX RSS
  50. <BR/><BR/>
  51.  
  52. <a href="#" onclick="showStuff('yahoo')" return false;>Click me for yahoo RSS</a><BR>
  53. <a href="#" onclick="showStuff('digg')" return false;>Click me for DIGG RSS</a>
  54.  
  55. <BR/><BR/>
  56. <div id="title"></div>
  57. <ul id="results">
  58. </ul>
  59.  
  60. </BODY>
  61. </HTML>



api/server.php

  1.  
  2. <?php
  3. require_once('JSON.php');
  4.  
  5. $JSON = new Services_JSON();
  6.  
  7. if($_POST['feed'] === 'yahoo') {
  8. $url = 'http://rss.news.yahoo.com/rss/topstories';
  9. } else {
  10. $url = 'http://digg.com/rss/index.xml';
  11. }
  12. /*---------------------------------------------------------------------------------------*/
  13. // grab the contents of the rss feed
  14.  
  15. $rss_file = file_get_contents($url);
  16.  
  17. // load up our simple xml object
  18. if(!$feed = simplexml_load_string($rss_file))
  19. {
  20. // you would send an error back up to the client for processing
  21. die("Cannot load RSS Feed. This application supports RSS 1.0 and 2.0");
  22. }
  23. /*---------------------------------------------------------------------------------------*/
  24.  
  25. //title of the feed
  26. $rss['title'] = (string)$feed->channel->title;
  27.  
  28. // check for RSS Version
  29. $items = ($feed['version'] != '') ? $feed->channel->item : $feed->item;
  30.  
  31. // PRINT OUT ITEMS
  32. foreach($items as $item)
  33. {
  34. $rss['items'][] = (string)$item->title;
  35. }
  36. echo $JSON->encode($rss);
  37. ?>
  38.  


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








Comments

RSS feed for comments on this post.

  1. Dennis Pallett says:
    January 13, 2006 @ 13:20 — Reply

    Yeah, that's pretty neat, but XML ain't that bad either, if you use a standard Ajax function (mine automatically changes a PHP array into a XML response).

  2. murali says:
    January 31, 2006 @ 05:32 — Reply

    Can I use the same concept with Asp.Net ?

  3. Jim Plush says:
    January 31, 2006 @ 08:40 — Reply

    definately, JSON isn't server language specific. All you need is a deserializer in .net which I'm sure there is at least one.

  4. fluffy says:
    February 8, 2006 @ 18:11 — Reply

    "*Ability to fetch JSON data from other domains which you can't do with xmlhttp alone" Why is this unique to using JSON? You can do exactly the same using XML or HTML? xmlhttp calls a local server script, the local server scripts calls a remote server and returns whatever it wants to the response right?

  5. Jim says:
    February 9, 2006 @ 07:20 — Reply

    fluffy, that technique works for smaller sites, but when you start getting into seriously heavy traffic you need to watch every byte you send over the wire. The slowest point in your app is usually all the network calls you make.

  6. Andrew Hedges says:
    November 15, 2006 @ 11:49 — Reply

    You beat me to it! We've been calling AJAX "AJAJ" internally here for a while. I've been meaning to write it up as a blog post. Glad to see others share our sense of acronymical humor!

  7. replica handbags says:
    January 29, 2010 @ 22:45 — Reply

    Comment pending moderation

  8. Anonymous says:
    January 31, 2010 @ 20:10 — Reply

    Comment pending moderation

  9. blu ray ripper says:
    April 18, 2010 @ 04:19 — Reply

    Comment pending moderation

  10. replica handbags says:
    April 22, 2010 @ 00:47 — Reply

    Comment pending moderation

  11. giochi online says:
    May 18, 2010 @ 10:04 — Reply

    Comment pending moderation

  12. virbram five fingers says:
    June 4, 2010 @ 20:28 — Reply

    Comment pending moderation

  13. authentic chanel handbags says:
    June 9, 2010 @ 06:22 — Reply

    Comment pending moderation

  14. Replica Jewelry says:
    June 21, 2010 @ 00:43 — Reply

    Comment pending moderation

  15. air max says:
    June 24, 2010 @ 02:01 — Reply

    Comment pending moderation

Leave a Comment

Line and paragraph breaks automatic, HTML allowed: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <code> <em> <i> <strike> <strong>

Comments disabled due to spammers being losers that lead sad lives.