views:

46

answers:

2

How to post data from a flex file to a php file? I am not able to create an action.

+5  A: 

Hello,

What you need is to create a URLRequest object where you set up your method and data to send. You then start the request with a Loader object.

var req:URLRequest = new URLRequest(yourURL);
req.method = URLRequestMethod.POST;
var vars:URLVariables = new URLVariables();
vars.yourVar = 'yourValue';
req.data = vars;
var ldr:Loader = new Loader();
ldr.load(req);
Alin Purcaru
+1  A: 

You need to create an HTTPService in order to send data to a server application like a PHP file from Flex. The data that is going to be sent could be an XML, that way in your PHP file you can parse that XML and get the information that is in it.

I use this function to transform my objects to XML and then send that XML in the HTTPService:

public function objectToXML(obj:Object, root:String):XML {
    var qName:QName = new QName(root);
    var xmlDocument:XMLDocument = new XMLDocument();
    var simpleXMLEncoder:SimpleXMLEncoder = new SimpleXMLEncoder(xmlDocument);
    var xmlNode:XMLNode = simpleXMLEncoder.encodeValue(obj, qName, xmlDocument);
    var xml:XML = new XML(xmlDocument.toString());
    return xml;
}

That way I create objects with normal properties and don't worry about how to create the XML, then when you are going to send the XML in the HTTPService you just call the method "objectToXML" on the send method of your HTTPService.

You do that like this:

var myData:Object=new Object();
myData.name="Information";

var myService:HTTPService = new HTTPService();
myService.url = "http://example.com/yourFile.php";
myService.method = "POST";
myService.contentType="application/xml";
myService.send(objectToXML(myData,"parent"));
edgsv