Using JSON and actionscript 3 to display a leaderboard, back-end php and MySQL

Categories Actionscript, JSON

I have worked with XML for many years, now I had a chance to use JSON on a little pice of a project. The documentation might be confusing for many people so here is a simple easy to understand use of JSON with actionscript 3 and php, MySQL.

The idea is to list the top 10 users in a MySQL database based on their score.

Here is how the php part looks like:

  1. < ?php include 'config.php'; include 'opendb.php'; $sql = "SELECT username, score FROM app_table ORDER BY score DESC LIMIT 10"; $result = mysql_query($sql); $objArray = array(); while ($row = mysql_fetch_assoc($result)) { $objArray[] = $row; } echo json_encode($objArray); include 'closedb.php'; ?>

The trick is to save each result in an array $objArray[] so you will be able to properly use the JSON object in actionscript as an array.

In flash you would have to put a data grid component on the stage (ctr+f7 to open the components panel), name it myDataGrid.

ActionScript

  1. var serverAdress:String = "http://yourserver/"
  2. myDataGrid.columns = ["username", "score"];
  3. var request:URLRequest = new URLRequest();
  4. request.url = serverAdress + "top.php?"+Math.random();
  5. request.requestHeaders=[new URLRequestHeader("Content-Type", "application/json")];
  6. request.method=URLRequestMethod.GET;
  7. var loader:URLLoader=new URLLoader();
  8. loader.addEventListener(Event.COMPLETE, receive);
  9. function receive(e:Event):void
  10. {
  11. var myResults:Object = JSON.parse(e.target.data);
  12.  
  13. for (var i:int = 0; i < myResults.length; i++)
  14. {
  15. myDataGrid.addItem(myResults[i]);
  16. }
  17.  
  18. }
  19. loader.load(request);

To see the top username you would do:

ActionScript

  1. trace(myResults[0].username);

Now I think this is a lot more simpler that dealing with XML, although XML might have it’s strong points, JSON is a lot smaller so especially when dealing with large sets of data, JSON will save bandwidth and also might save some processing time on the client (I have to test this out).

Share this
Facebooktwitter