Thursday, December 17, 2009

Pass data between Facebook PHP app and Flex

I am writing a Facebook Connect application using Flex for front-end with the backend in PHP. This is what my PHP file looks like:

 <?php  
 //filename = "talktofb.php"  
 include_once "facebook.php";  
 $facebook = new Facebook("", "");  
 $ret = $facebook->api_client->fql_query ( "SELECT post_id, message, source_id, attachment from stream where filter_key='nf' and type=46 and source_id in(Select uid from user where uid in (select uid2 from friend where uid1= )) limit 1,5" );  
 echo json_encode($ret);  
 ?>  
This returns the stream of my friends for me (Please note this is for demo only - do not use "type" in your FQL query since this is deprecated )

I use json_encode to return a Javascript/JSON style name-value pair associative array

This PHP code is executed by the Flex application and results retrieved

 <?xml version="1.0" encoding="utf-8"?>  
 <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"   
   layout="absolute">  
 <mx:Script>  
 <![CDATA[  
  import com.adobe.serialization.json.JSON;  
  public function OnResult():void {  
      var arr:Array = (JSON.decode(userRequest.lastResult.toString()) as Array);  
      for (var i:int=0;i<arr.length;i++){  
                     trace (arr[i].post_id);  
      }   
  }  
      ]]>  
 </mx:Script>  
 <mx:HTTPService id="userRequest"   
         url="http://localhost/talktofb.php"   
                     useProxy="false"   
                     method="POST"   
                     result="OnResult()"/>  
 <mx:Button click="userRequest.send();"   
             label="ClickMe!" width="185" height="42"/>  
 </mx:Application>  
I am using the mx:HTTPService tag to load the PHP script. In order to use the JSON encoded data, I am using as3corelib library. It hasn't been updated for a while but it does the work I need.

In order to make the library available in Flex Builder, you need to unzip the file to a folder, then add it to Menu -> Project -> Properties -> Flex Build Path -> Library Path -> Add SWC... Locate the SWC file in ../as3corelib-.92.1/lib/as3corelib.swc

This is probably not the best way to do it but this is just a quick how-to - took me a full day to figure this out - I hope this helps someone else too

No comments:

Followers