Flex & PHP – Transmitting data using JSON


In almost every RIA data needs to be transmitted from a server to the client. Now there are many ways to accomplish this task—web services, HTTP requests, remote objects, etc. But one sticks out as a simplistic and useful solution to this problem, this is using HTTP requests. Using a simple HTTP request, you can send data to a server and receive data back from the server.

Adobe Flex makes implementing this solution an easy task. The solution explained in this tutorial uses PHP for the server-side programming and sends the data using JSON (JavaScript Object Notation) encoding. By the end of the tutorial you will be sending simple objects along with arrays of objects from your PHP code to your Flex client.

Requirements

Flex Builder 2 (or Flex 2 SDK)

PHP (version 5.2 or higher, installed on a local web server)

Adobe Flex corelib

Sample files:

This sample file contains the following:

  • Flex Builder project with source
  • PHP source code
  • corelib.swc

Prerequisite knowledge

To benefit most from this tutorial, it is best if you have:

  • Built simple Flex applications before
  • A basic understanding of PHP
  • A basic knowledge of JSON

Setting up the development environment

This is actually a lot easier than it sounds because PHP and Flex both have functions to handle JSON data transmissions. For Flex, the one thing you need to make sure is that you have the corelib from Adobe in order to use the JSON functions—you can download it from Adobe Flex corelib. You can add this to a project in Flex Builder by going into the properties of a project then to “Flex Build Path” and adding the .swc to the library path. For PHP, if you have a version greater than 5.2, you are all set. If not, you can either upgrade, or install the php-json extension.

At this point you can also open up the provided ZIP file and you will find a couple of items. The first is the Flex source code that was used to create the application. You will also find the corelib library that is used in this project under the lib folder. You can proceed in multiple ways from here: create a new Flex Project in Flex Builder and then add the source and lib directory or use the SDK binaries to compile the application. Once it is built, it can be run and this will get data from a PHP file on the Paranoid Ferret server. I will go over the source code for both the PHP and Flex in depth later on in the tutorial.

Getting the PHP code ready

The first thing we are going to go over is the PHP code (json_tutorial.php), which you can find in the sample ZIP file. The PHP code creates a few classes for the objects that we will pass to our Flex application. We also have code to check if a GET variable has been set. We use this to tell the PHP code what we are requesting. If the variable getPerson is set, we create a person and echo it (after we encode it into JSON using json_encode) to send it to the Flex application. Ideally your data would be stored in a database, but for simplicity, we’re just creating Person objects directly in the PHP code.

The following is all the PHP code we are going to use and should meet our needs:

<?php
    
    class Person
    {
        public $first_name;
        public $last_name;
        public $email;
        public $address;
    }
    
    class Manager extends Person
    {
        public $title;
        public $employees;
    }
    
    if(isset($_GET['getPerson']))
    {
        $p = new Person();
        $p->first_name = 'John';
        $p->last_name = 'Doe';
        $p->email = 'fake@email.com';
        $p->address = '5555 Some Street City, State 52423';
        echo json_encode($p);
    }
    
    if(isset($_GET['getManager']))
    {
        $p1 = new Person();
        $p1->first_name = 'Joe';
        $p1->last_name = 'Doe';
        $p1->email = 'joe.doe@email.com';
        $p1->address = '5424 Some Street City, State 12314';
        $p2 = new Person();
        $p2->first_name = 'Bob';
        $p2->last_name = 'Doe';
        $p2->email = 'bob.doe@email.com';
        $p2->address = '1414 Some Street City, State 12412';
        $p3 = new Person();
        $p3->first_name = 'Kevin';
        $p3->last_name = 'Doe';
        $p3->email = 'kevin.doe@email.com';
        $p3->address = '6123 Some Street City, State 41241'; 
      
        $m = new Manager();
        $m->first_name = 'Manager';
        $m->last_name = 'Doe';
        $m->email = 'manager.doe@email.com';
        $m->address = '5534 Some Other Street City, State 91230';
        $m->title = 'Office Manager';
        $m->employees = array($p1, $p2, $p3);
        echo json_encode($m);
        
    }
    ?>

Creating the Flex user interface

The next thing to do is to set up the basic application for Flex. All the code from here on is found in the JSONTutorial.mxml file in the Flex Builder Project included in the sample ZIP file. The following code is the simplest Flex application. This sets up an application with specified height and width and also adds the view source option to the movie, with the source file specified by viewSourceURL. The URL can be any path that points to the correct file to display the source code:

<?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="500" height="410" 
    viewSourceURL="../files/JSONTutorial.mxml">
    </mx:Application>

The next thing you do is to set up the user interface. This is pretty standard Flex mxml. Nothing should look out of place. The user interface has a couple of text fields for the data we get back from the PHP code, a datagrid, and two buttons. This is all set up on a panel. The one important thing to observe is the dataField properties on the DataGridColumns. These names correspond to the variables from the objects in the PHP code.

The following code goes inside the Application block:

<mx:Panel x="0" y="0" width="500" height="410" layout="absolute" title="Simple JSON Example">
        <mx:DataGrid x="10" y="174" width="460" enabled="true" editable="false" id="dgEmployees">
            <mx:columns>
                <mx:DataGridColumn headerText="First Name" dataField="first_name"/>
                <mx:DataGridColumn headerText="Last Name" dataField="last_name"/>
                <mx:DataGridColumn headerText="Email" dataField="email"/>
                <mx:DataGridColumn headerText="Address" dataField="address"/>
            </mx:columns>
        </mx:DataGrid>
        <mx:Button x="116" y="338" label="Get Employee" id="getPerson" />
        <mx:Button x="266" y="338" label="Get Manager" id="getManager" />
        <mx:Label x="131" y="12" text="Name"/>
        <mx:TextInput x="189" y="10" id="txtName" editable="false"/>
        <mx:Label x="131" y="42" text="E-mail"/>
        <mx:TextInput x="189" y="40" id="txtEmail" editable="false"/>
        <mx:Label x="131" y="68" text="Address"/>
        <mx:TextInput x="189" y="66" id="txtAddress" editable="false"/>
        <mx:Label x="131" y="94" text="Title"/>
        <mx:TextInput x="189" y="92" id="txtTitle" editable="false"/>
        <mx:Label x="131" y="122" text="Has Employees"/>
        <mx:TextInput x="229" y="120" width="120" editable="false" id="txtEmployees" text="No"/>
        <mx:Label x="10" y="148" text="Employees:"/>
    </mx:Panel>

Using HTTPService to ask PHP for data

Now that the user interface is set up and ready to go you can add the HTTP services to go ask for the data from the PHP code. In Flex you can set up all kinds of different services. Today you are just going to set up a simple HTTP request service that sets a GET variable and tells the services a function should be ran once the results are back. As you can see in the code below, both services are sending out to the same PHP page, which is the one that was made earlier. Also each one sets one GET variable, which is done inside the mx:request block. Lastly, the result is an event which we hook to, to process the results of the request (our JSON data). This code goes at the very beginning of the file right after the Application opening element:

<mx:HTTPService id="personRequest" 
        url="../files/json_tutorial.php" 
        useProxy="false" method="GET" resultFormat="text" 
        result="personJSON(event)">
        <mx:request xmlns="">
            <getPerson>true</getPerson>
        </mx:request>
    </mx:HTTPService>
    <mx:HTTPService id="managerRequest" 
        url="../files/json_tutorial.php" 
        useProxy="false" method="GET" resultFormat="text" 
        result="managerJSON(event)">
        <mx:request xmlns="">
            <getManager>true</getManager>
        </mx:request>
</mx:HTTPService>

Decoding the JSON data

Now you can get into the actual JSON decoding, which is really simple. At this point if you’re using Flex Builder you will be getting an error message about an undefined method for personJSON(event) and managerJSON(event). This is going to be solved right now. First things first—put in the appropriate method signatures so the application can build and run. You do this by inputting a script tag and adding the ActionScript functions inside of it. You’ll notice the added import statements, in the code, to import our JSON serialization functions and use the result event. This code will go right above the HTTP services we just set up and below the Application opening element:

<mx:Script>
        <![CDATA[
        import mx.rpc.events.ResultEvent;
        import com.adobe.serialization.json.JSON;
        
        private function personJSON(event:ResultEvent):void
        {
        }
        
        private function managerJSON(event:ResultEvent):void
        {
        }
        ]]>
</mx:Script>

Now down to the actual work of the application, the first thing that needs to be done in both of the functions is to get the result back and store it as a string. The next thing to do is to call the function JSON.decode on the string. This function will return us an object with all the same properties of the one sent by PHP—we set this equal to a variable. This can now be used as a normal object and to reference the properties using the . (dot) notation. To get the first name of the person you can simply use variable.first_name and so on for the rest of the variables. This takes care of getting a person from PHP. And the above code is changed like so:

<mx:Script>
        <![CDATA[
        import mx.rpc.events.ResultEvent;
        import com.adobe.serialization.json.JSON;
        
        private function personJSON(event:ResultEvent):void
        {
            //get the raw JSON data and cast to String
            var rawData:String = String(event.result);
            var person:Object = JSON.decode(rawData);
            txtName.text = person.first_name + " " + person.last_name;
            txtEmail.text = person.email;
            txtAddress.text = person.address;
            txtEmployees.text = "No";
            txtTitle.text = "No Title";
        }
        
        private function managerJSON(event:ResultEvent):void
        {
            //get the raw JSON data and cast to String
            var rawData:String = String(event.result);
            var manager:Object = JSON.decode(rawData);
            txtName.text = manager.first_name + " " + 
                     
            manager.last_name;
            txtEmail.text = manager.email;
            txtAddress.text = manager.address;
            txtEmployees.text = "Yes";
            txtTitle.text = manager.title;
        }
        ]]>
</mx:Script>

Hooking data to datagrid

All that is left is to worry about the datagrid you created, and you might have noticed that employees of the manager haven’t been dealt with yet. This is handled pretty nicely in the manager function. You are going to add a new var called employees and this will be an array. Because of the JSON.decode function, you can simply cast the employees as an array and all will be fine.

The next thing to do is actually creating an ArrayCollection to use for the data provider for the datagrid. This is a best practice when using array data for the provider because the ArrayCollection allows for some extra functionality. The final setup is to set the dataGrid.dataProvider equal to the ArrayCollection. You also set the dataProvider equal to null in the person function to clear out the data in the datagrid. To make all this work you need to add another import statement for ArrayCollection. This leaves you with the following code:

<mx:Script>
        <![CDATA[
        import mx.collections.ArrayCollection;
        import mx.rpc.events.ResultEvent;
        import com.adobe.serialization.json.JSON;
        
        private function personJSON(event:ResultEvent):void
        {
            //get the raw JSON data and cast to String
            var rawData:String = String(event.result);
            var person:Object = JSON.decode(rawData);
            txtName.text = person.first_name + " "  + person.last_name;
            txtEmail.text = person.email;
            txtAddress.text = person.address;
            txtEmployees.text = "No";
            txtTitle.text = "No Title";
            
            //Data Grid Code
            dgEmployees.dataProvider = null;
        }
        
        private function managerJSON(event:ResultEvent):void
        {
            //get the raw JSON data and cast to String
            var rawData:String = String(event.result);
            var manager:Object = JSON.decode(rawData);
            txtName.text = manager.first_name + " " + manager.last_name;
            txtEmail.text = manager.email;
            txtAddress.text = manager.address;
            txtEmployees.text = "Yes";
            txtTitle.text = manager.title;
            
            //Data Grid Code
            var employees:Array = manager.employees as Array;
            var employeesCollection:ArrayCollection = new ArrayCollection(employees); 
            dgEmployees.dataProvider = employeesCollection;
        }
        ]]>
    </mx:Script>

Now you might have tried it at this point and said, “Hey, this isn’t working!”. That is true. This is because you never hooked the buttons up to send the requests. This is really simple. You just add click events for both buttons and the corresponding service.send() commands to the click events. The following code replaces the old buttons:

<mx:Button x="116" y="338" label="Get Employee" id="getPerson" click="personRequest.send();"/>
<mx:Button x="266" y="338" label="Get Manager" id="getManager" click="managerRequest.send();"/>

Finally this puts the whole thing together and we end up with the following code for our Flex application:

<?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    layout="absolute" width="500" height="410" 
    viewSourceURL="../files/JSONTutorial.mxml">
    <mx:Script>
    <![CDATA[
    import mx.collections.ArrayCollection;
    import mx.rpc.events.ResultEvent;
    import com.adobe.serialization.json.JSON;
    
    private function personJSON(event:ResultEvent):void
    {
        //get the raw JSON data and cast to String
        var rawData:String = String(event.result);
        var person:Object = JSON.decode(rawData);
        txtName.text = person.first_name + " " + person.last_name;
        txtEmail.text = person.email;
        txtAddress.text = person.address;
        txtEmployees.text = "No";
        txtTitle.text = "No Title";
        
        //Data Grid Code
        dgEmployees.dataProvider = null;
    }
    
    private function managerJSON(event:ResultEvent):void
    {
        //get the raw JSON data and cast to String
        var rawData:String = String(event.result);
        var manager:Object = JSON.decode(rawData);
        txtName.text = manager.first_name + " " + manager.last_name;
        txtEmail.text = manager.email;
        txtAddress.text = manager.address;
        txtEmployees.text = "Yes";
        txtTitle.text = manager.title;
        
        //Data Grid Code
        var employees:Array = manager.employees as Array;
        var employeesCollection:ArrayCollection = new ArrayCollection(employees); 
        dgEmployees.dataProvider = employeesCollection;
    }
    ]]>
</mx:Script>
    <mx:HTTPService id="personRequest" url="../files/json_tutorial.php" 
        useProxy="false" method="GET" resultFormat="text" 
        result="personJSON(event)">
        <mx:request xmlns="">
            <getPerson>"true"</getPerson>
        </mx:request>
    </mx:HTTPService>
    <mx:HTTPService id="managerRequest" 
        url="../files/json_tutorial.php" 
        useProxy="false" method="GET" resultFormat="text" 
        result="managerJSON(event)">
        <mx:request xmlns="">
            <getManager>"true"</getManager>
        </mx:request>
    </mx:HTTPService>
    <mx:Panel x="0" y="0" width="500" height="410" layout="absolute" title="Simple JSON Example">
        <mx:DataGrid x="10" y="174" width="460" enabled="true" 
        editable="false" id="dgEmployees">
            <mx:columns>
                <mx:DataGridColumn headerText="First Name" dataField="first_name"/>
                <mx:DataGridColumn headerText="Last Name" dataField="last_name"/>
                <mx:DataGridColumn headerText="Email" dataField="email"/>
                <mx:DataGridColumn headerText="Address" dataField="address"/>
            </mx:columns>
        </mx:DataGrid>
        <mx:Button x="116" y="338" label="Get Employee" id="getPerson" click="personRequest.send();"/>
        <mx:Button x="266" y="338" label="Get Manager" id="getManager" click="managerRequest.send();"/>
        <mx:Label x="131" y="12" text="Name"/>
        <mx:TextInput x="189" y="10" id="txtName" editable="false"/>
        <mx:Label x="131" y="42" text="E-mail"/>
        <mx:TextInput x="189" y="40" id="txtEmail" editable="false"/>
        <mx:Label x="131" y="68" text="Address"/>
        <mx:TextInput x="189" y="66" id="txtAddress" editable="false"/>
        <mx:Label x="131" y="94" text="Title"/>
        <mx:TextInput x="189" y="92" id="txtTitle" editable="false"/>
        <mx:Label x="131" y="122" text="Has Employees"/>
        <mx:TextInput x="229" y="120" width="120" editable="false" id="txtEmployees" text="No"/>
        <mx:Label x="10" y="148" text="Employees:"/>
    </mx:Panel>
    </mx:Application>

You now have a small application that will get data from PHP using JSON.

Where to go from here

After learning the basics of sending data from PHP to Flex using JSON, you might still have some yearning for learning. (Oh, that is cheesy!) If you are still looking for more information on transmitting data between Flex and PHP I recommend you to go to http://blog.paranoidferret.com and check out some of the other Flex and PHP tutorials out there.

If you want to explore other possible solutions to transmitting data, check the tutorial Using Flex 2 and AMFPHP by Mike Potter in the Flex Developer Center.

Lastly if you found some of this to go over your head, check out the other tutorial by Mike Potter on Flex 2 and PHP basics, Integrating Flex 2 and PHP.

Bookmark and Share
  1. Nice Post And thanks For the Complete explanation with Code
    flex development india

    • Gary
    • February 8th, 2012

    02/08/2012 – 11:45
    If add:

    <?php

    include ('header.php'); // add here

    class Person
    {
    public $first_name;
    public $last_name;
    public $email;
    public $address;
    }

    it breaks. why is that?

    how can i get another variable from another PHP file?

  2. Such people are chromosomally male (one X and one Y chromosome), but they are resistant to androgens, the hormones that are responsible for
    male sexual development. So goes the theory of time and space
    by Einstein. All you have to do is to conduct extensive research
    on the internet, put side by side the features of different paid versions and then buy the software program.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: