Posts Tagged ‘json’

Actionscript -> JSON -> PHP

Posted in Flex/ActionScript on December 23rd, 2009 by admin – Be the first to comment

Lately I have been using a tool a lot that I wrote some months ago, so I thought I better share it with the rest of the world. It’s a tool for sending and receiving Objects between a Flash/Flex client and a PHP server.

objectFromServer:

function objectFromServer(url:String, data:Object, handler:Function):void {
    var loader:URLLoader = new URLLoader();
    var requester:URLRequest = new URLRequest();
    requester.method = URLRequestMethod.POST;
    loader.addEventListener(Event.COMPLETE, function(event:Event):void {
        var tempLoader:URLLoader = URLLoader(event.target);
        var obj:Object = JSON.decode(tempLoader.data);
        handler(obj);
    });
    loader.addEventListener(IOErrorEvent.IO_ERROR, function(event:IOErrorEvent):void {
        Alert.show("ioErrorHandler: " + event);
    });
    loader.dataFormat = URLLoaderDataFormat.TEXT;
    requester.url = url;
    var variables:URLVariables = new URLVariables();
    variables.json = JSON.encode(data);
    requester.data = variables;
    loader.load(requester);
}

You will need to download as3corelib.swc from http://code.google.com/p/as3corelib/ and add it to your project’s libary path.
This is how you add it in Flex Builder: Properties->Flex Build Path->Libary path->Add SWC…

I have written a simple test program to show how objectFromServer is used.

ActionScript:

setInterval(function():void {
    objectFromServer("/tests/objectFromServer.php", {name: "Mikkel"}, function(o:Object):void {
        myLabel.text = o.text as String;
    });
}, 3000);

PHP:

<?php
$o = json_decode($_POST["json"]);
$result = array("text" => "Hello ".$o->name.", server time is " . time());
echo json_encode($result);
?>

Demo:

The Flash plugin is required to view this object.