Wednesday, February 23, 2011

Array Transfer from flex to php via HttpService

Convert your array into a String of elements and separators using the "join" command. Then send the string via HTTPSERVICE.In PHP use the "split" command on the string passed from flex and store the result into an array.  
   
FLEX CODE:
//ArrayTransfer.mxml


<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:HTTPService id="sample" url=http://localhost/sample.php useProxy="false" method="POST"/>
<mx:Script>
      <![CDATA[
public var array:Array=new Array("9","13","14","17","60");

public function buttonClickHandler(event:Event):void
               {
                  var str:String=array.join(",");// this converts into a string  eg. "9,13,14,17,60"
                  trace(str);
                  sample.request.str1=str;//'str' can be referred as 'str1' in PHP 
                  sample.send();
                    sample.addEventListener(ResultEvent.RESULT,traverse);
                }
public function traverse(e:ResultEvent):void
               {
                  for(var i:int=0;i<4;i++)
               trace(sample.lastResult.arraying.array[i]);
               }  ]]>
</mx:Script>
<mx:Button id="viewdate"  label="viewdata" click="buttonClickHandler(event)"/>
</mx:WindowedApplication>

PHP CODE:
//Sample.php

Step1:initialize the hostname ,username and password .
Step2:start the connection and the following code.

$connection = mysql_connect($hostname,$username,$password) or die("Could not connect to host.");
$selected = mysql_select_db($database,$connection) or die("Could not find database.");
$numbers = split(',', $_POST['str1']); //str1 is the string passed from flex
$len=count($numbers);
$Return .="<arraying>";
for($i=0;$i<($len-1);$i++)
$Return .="<array>".$numbers[$i]."</array>";
$Return .= "</arraying>";
mysql_close();
print ($Return)