How to send or receive JSON encoded data from flash to a server-side-script
As contributor in some flash-related forums i noticed, that a lot of people are asking
the same question over and over again.
How to send or receive JSON-encoded data from flash to a server-side-script
In this little “tutorial” we’ll send an arbitrary JSON-encoded Object from flash
to our server-script, alter the value of its property and send it; even JSON encoded;
back from the server to flash.
First we need to know how the object looks like:
12
varperson:Object=newObject();person.age=17;// this is the property we want to change
Now let’s do the server-side script which receives and sends our JSON endcoded data.
<?php//// only continue if data is sent in the 'data' property//if(!empty($_REQUEST['data'])){//// retrieve the sent data//$data=urldecode(utf8_decode(stripslashes($_REQUEST['data'])));//// re-create the sent object <code>person</code>//$decoded_person=json_decode($data);//// the ravages of time//happy_birthday($decoded_person);//// prepare the data for sending back to flash//$encoded_person=json_encode($decoded_person);//// send//print($encoded_person);}//// increase the <code>age</code> property// of <code>person</code> and return the object//functionhappy_birthday($person){(int)$person->age++;return$person;}?>
importcom.adobe.serialization.json.JSON;//// URLLoader event-handler//function completeHandler(e:Event):void{trace('::complete()');trace('--received: '+e.target.data);}function ioHandler(evt:IOErrorEvent):void{trace("::IOError()n"+evt.text);}function securityHandler(evt:SecurityErrorEvent):void{trace("::SecurityError()n"+evt.text);}//// setup the data we want to send//varperson:Object=newObject();person.age=17;varencoded_person:String=JSON.encode(person);trace('--sending: '+encoded_person);// {"age":17}//// encode and store the data//varvars:URLVariables=newURLVariables();vars.data=JSON.encode(person);varrequest:URLRequest=newURLRequest();request.url="http://localhost/data.php";request.data=vars;request.method=URLRequestMethod.POST;//// add event listener and sent the encoded data//varloader:URLLoader=newURLLoader();loader.addEventListener(Event.COMPLETE,completeHandler);loader.addEventListener(IOErrorEvent.IO_ERROR,ioHandler);loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,securityHandler);loader.load(request);
If all’s gone well you should see the following output..
Now you just need to decode the data in the completeHandler like so, and you’ll have your object with the changed value.
123456789101112131415
function completeHandler(e:Event):void{trace('::complete()');trace('--received: '+e.target.data);try{varperson:Object=JSON.decode(e.target.data);trace('--age is now: '+person.age);// 18}catch(e:Error){trace('ERROR - could not decode data..');}}
and thats it..
If you find this useful feel free to share or leave a comment if you like.
Thanks for reading..