Passing Variables from Flash to PHP - php

Creating a flash project where users can visit the site, and turn off/on objects in a house (ie. lights, tv, computer, etc.) The next user who will visit the house in the website, will see what lights or house appliances were left on. Flash variables are passed to PHP, and those variables are saved in an XML file. (For testing to see what is being saved to the XML file, on each click --vars.xml opens.) In the vars.xml file, I see that the house objects that were last turned on--are saved in the XML file--BUT in the SWF file, ONLY one of the objects that are listed in the XML are turned ON. Only the last object that was clicked on would show ON--not all the objects in the XML file.)
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.text.*;
import flash.net.*;
public class House extends MovieClip {
var request:URLRequest = new URLRequest("vars.xml")
var loader:URLLoader = new URLLoader();
// Constructor--------------------------------------------------------------------
public function House()
{
loader.addEventListener(Event.COMPLETE, parseXML);
loader.load(request);
}
// function sendPhp ------------------------------------------------------------------
function sendPhp():void
{
// send vars to php
var request:URLRequest = new URLRequest("write_xml.php"); // the php file to send data to
var variables:URLVariables = new URLVariables(); // create an array of POST vars
for (var i:int=0; i<onList.length; i++) {
variables["v"+i] = onList[i];
}
//variables['powerUsage'] = totalTxt.text;
request.data = variables; // send the vars to the data property of the requested url (our php file)
request.method = URLRequestMethod.POST; // use POST as the send method
try
{
var sender:URLLoader = new URLLoader();
sender.load(request); // load the php file and send it the variable data
navigateToURL(new URLRequest("vars.xml"), '_blank'); //show me the xml
}
catch (e:Error)
{
trace(e); // trace error if there is a problem
}
}
// function parseXML ------------------------------------------------------------------
function parseXML(evt:Event)
{
var xdata:XML = new XML(loader.data); // using E4x
//xdata.child(0);
for (var j:int=0; j<xdata.length(); j++) {
onList[j] = xdata.child(j);
for (var k:int=0; k<HouseObjects.length;k++) {
//root[onList[j]].gotoAndStop(3);
if (onList[j] == HouseObjects[k].name) {
HouseObjects[k].gotoAndStop(3);
//trace("tracing house objects"+ HouseObjects[k]);
trace("onList[j]: " + onList[j]);
trace("Array onList: " + onList);
}
}
}
}
} //end of class
} // end of package

You actually don't need to put all this code here, and it's true that you should make your app more secure , especially after showing all this info! If your XML is not the problem , check the Actionscript part, particularly the parseXML() function.
Are you able to trace the names of the components that are switched on? If yes , concentrate on what's happening in your loop. If your xml is fine, the problem is not passing data from PHP to Flash.
I like the tree house! ;)

Related

AS3. Unable to connect SWF with PHP in order to process a flashvar

here 5:44 am , all night up trying to make this work.
Im trying to send a URL from a swf file to a php file, process that URL with the php code and return it to the swf.
I succeeded on sending and procesing the data. The problem arrives when I try to use the data on the actionScript code.
//videoSrc is a string containing the URL I want to process.
videoSrc=modifySrc(videoSrc);
function modifySrc(vSrc:String):String{
// Assign a variable name for our URLVariables object
var variables:URLVariables = new URLVariables();
// Build the varSend variable
// Be sure you place the proper location reference to your PHP config file here
var varSend:URLRequest = new URLRequest("http://foo.net/config_flash.php");
varSend.method = URLRequestMethod.POST;
varSend.data = variables;
// Build the varLoader variable
var varLoader:URLLoader = new URLLoader;
varLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
varLoader.addEventListener(Event.COMPLETE, completeHandler);
variables.uname = vSrc;
variables.sendRequest = "parse";
// Send the data to the php file
varLoader.load(varSend);
// the php function ends with ' print "var1=$UrlProcessed"
function completeHandler(event:Event):void{
vSrc = event.target.data.var1;
}
return vSrc;
}
The problem is that vSrc never changes. I think the problem is related to this line:
varLoader.addEventListener(Event.COMPLETE, completeHandler);
I'm not being able to make completeHandler modify vSrc value.
That's because network requests are asynchronous. The return value from modifySrc remains unchanged while the function is executing. It only changes when the URLLoader instance triggers a Event.COMPLETE event. Try this instead:
modifySrc(videoSrc);
function modifySrc(src:String):void
{
...
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, modify_completeHandler);
...
}
function modify_completeHandler(event:Event):void
{
var loader:URLLoader = event.target as URLLoader;
loader.removeEventListener(Event.COMPLETE, modify_completeHandler);
videoSrc = loader.data.var1;
}
I've truncated the rest of your initialization code from modifySrc for brevity.

How do i POST a variable value to a php file?

i need to send a variable value from a simple flash program to a php file or my database, i found this code online for that
var loader:URLLoader = new URLLoader();
loader.addEventListener( Event.COMPLETE, completeHandler );
var variables:URLVariables = new URLVariables();
variables.someVar = "someValue";
var request:URLRequest = new URLRequest("myPhpPage.php");
request.method = URLRequestMethod.POST;
request.data = variables
loader.load(request);
function completeHandler( event : Event ) : void{
trace( "finished sending and loading" );
}
but if i make a simple program with one button which raises the value or 'p' by one for every click with the code
on (press) {
i ++;
}
and i put that code for post in the frame actions window i get error messages. One of them is 'The class or identifier 'URLLoader' could not be loaded.' i also can't load URLVariables , Events and URLRequest. Please tell me what i am missing here.
Make sure you have the proper imports to use the classes such as URLLoader and URLVariables. Check adobe site to see what package they come from
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLLoader.html
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLVariables.html
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLRequest.html
We see that they all come from the flash.net package. You would want to make sure to import the package like so:
import flash.net.*;

Loading files with extension data from POST send - php as3

I'm trying to work out from an old as2 tutorial how to amend a script for as3/php eCard system for a business card but I can't find reference anywhere to how you'd do the following :
AS2 :
loadVariablesNum ("http://www.theSite.com/Cards/bCard/"+BcardText+".txt", 0);
AS3 :
// setup URLLoader
var loader:URLLoader = new URLLoader;
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
// event listener for function when loaded
loader.addEventListener(Event.COMPLETE, varsLoaded);
// file URLRequest
loader.load(new URLRequest("http://www.theSite.com/Cards/bCard/"+BcardText+".txt"));
// set the variables from the data.txt file
function varsLoaded (event:Event):void {
//Load Data
cName.text = loader.data.cName;
cDescription.text = loader.data.cDescription;
}
With this it kicks out the following error message :
Error opening URL 'http://www.theSite.com/Cards/bCard/undefined.txt'
Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
at Error$/throwError()
at flash.net::URLVariables/decode()
at flash.net::URLVariables()
at flash.net::URLLoader/onComplete()
I can't work out where or how you define the +BcardText+ for it to pull it in.
Any help would be gratefully received.
I'm not sure If I'm even close as its from as2, it seems the logical approach for loading it but I've not dealt with external files having parameters before.
Thanks in advance if anyone can help out in anyway!
NEW LOADER - FIXED!!!
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("http://www.theSite.com/Cards/bCard/"+BcardText+".txt");
loader.load(request);
loader.addEventListener(Event.COMPLETE, completeHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, loaderIOErrorHandler);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
function loaderIOErrorHandler(event:IOErrorEvent):void{
trace("ioErrorHandler: " + event);
}
// set the variables from the .txt file
function completeHandler (event:Event):void {
//trace("Content: " + loader.data);
this.Variable1.text = loader.data.Variable1; //Whatever dataField1 you saved as
this.Variable2.text = loader.data.Variable2; //Whatever dataField2 you saved as
}
Then you just setup FlashVars to distinguish the +BcardText variable in the loader prior to committing it!
BcardText was a variable defined in the as2 project. Look around (maybe on previous frames?) and you should find where it got declared. It looks like an ID to represent the card. So each card has a unique file 12345.txt, 09876.txt etc.
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("http://www.theSite.com/Cards/bCard/"+BcardText+".txt");
loader.load(request);
loader.addEventListener(Event.COMPLETE, completeHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, loaderIOErrorHandler);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
function loaderIOErrorHandler(event:IOErrorEvent):void{
trace("ioErrorHandler: " + event);
}
// set the variables from the .txt file
function completeHandler (event:Event):void {
//trace("Content: " + loader.data);
this.Variable1.text = loader.data.Variable1; //Whatever dataField1 you saved as
this.Variable2.text = loader.data.Variable2; //Whatever dataField2 you saved as
}
Then you just setup FlashVars to distinguish the +BcardText variable in the loader prior to committing it!
Have scoured the Internet and gone half mad working this out but finally chuffed to say I broke it's back...!
A big thanks for helping point me in the right direction guys. #Jason #Eugen
Θ)

Post data to url without navigating to it?

I'm completely new to Flash and AS3. I've Googled around an cannot find anything on this topic.
I have some code that posts an image to a php file:
var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
var jpgURLRequest:URLRequest = new URLRequest("http://127.0.0.1/gdipORG/takeImage.php");
jpgURLRequest.requestHeaders.push(header);
jpgURLRequest.method = URLRequestMethod.POST;
jpgURLRequest.data = byteArray;
navigateToURL(jpgURLRequest, "blank");
Problem is, for the actual posting to take place, I have to navigate to the actual url (see last line of code)...
I want to be able to post the data to the url without having to navigate to it. Any ideas?
Use a URLLoader right after your existing code:
//Existing code
var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
var jpgURLRequest:URLRequest = new URLRequest("http://127.0.0.1/gdipORG/takeImage.php");
jpgURLRequest.requestHeaders.push(header);
jpgURLRequest.method = URLRequestMethod.POST;
jpgURLRequest.data = byteArray;
//KILL THIS LINE navigateToURL(jpgURLRequest, "blank");
//Add these (UNTESTED CODE):
var sendJPGLoader:URLLoader = new URLLoader();
sendJPGLoader.dataFormat = URLLoaderDataFormat.BINARY;
sendJPGLoader.addEventListener(Event.COMPLETE, sendJPGToServerComplete);
sendJPGLoader.addEventListener(IOErrorEvent.IO_ERROR, sendJPGToServerIOError);
//Try to send image
sendJPGLoader.load(jpgURLRequest);
function sendJPGToServerComplete(evt:Event):void {
//Request was sent to server succesfully
//Optionally check server response
// var serverResponse:String = String(evt.target.data);
}
function sendJPGToServerIOError(evt:Event):void {
//Failed
}
At the top of your code don't forget to import:
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
I think I got them all :)

Actionscript multiple file upload, with parameter passing is not working

First off, I am very bad at flash/actionscript, it is not my main programming language.
I have created my own file upload flash app that has been working great for me up until this point. It uses PHP to upload the files and sends back a status message which gets displayed in a status box to the user.
Now I have run into a situation where I need the HTML to pass a parameter to the Actionscript, and then to the PHP file using POST. I have tried to set this up just like adobe has it on http://livedocs.adobe.com/flex/3/html/help.html?content=17_Networking_and_communications_7.html without success.
Here is my Actionscript code
import fl.controls.TextArea;
//Set filters
var imageTypes:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg; *.jpeg; *.gif; *.png");
var textTypes:FileFilter = new FileFilter("Documents (*.txt, *.rtf, *.pdf, *.doc)", "*.txt; *.rtf; *.pdf; *.doc");
var allTypes:Array = new Array(textTypes, imageTypes);
var fileRefList:FileReferenceList = new FileReferenceList();
//Add event listeners for its various fileRefList functions below
upload_buttn.addEventListener(MouseEvent.CLICK, browseBox);
fileRefList.addEventListener(Event.SELECT, selectHandler);
function browseBox(event:MouseEvent):void {
fileRefList.browse(allTypes);
}
function selectHandler(event:Event):void {
var phpRequest:URLRequest = new URLRequest("ajax/upload.ajax.php");
var flashVars:URLVariables = objectToURLVariables(this.root.loaderInfo);
phpRequest.method = URLRequestMethod.POST;
phpRequest.data = flashVars;
var file:FileReference;
var files:FileReferenceList = FileReferenceList(event.target);
var selectedFileArray:Array = files.fileList;
var listener:Object = new Object();
for (var i:uint = 0; i < selectedFileArray.length; i++) {
file = FileReference(selectedFileArray[i]);
try {
file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, phpResponse);
file.upload(phpRequest);
}
catch (error:Error) {
status_txt.text = file.name + " Was not uploaded correctly (" + error.message + ")";
}
}
}
function phpResponse(event:DataEvent):void {
var file:FileReference = FileReference(event.target);
status_txt.htmlText += event.data;
}
function objectToURLVariables(parameters:Object):URLVariables {
var paramsToSend:URLVariables = new URLVariables();
for(var i:String in parameters) {
if(i!=null) {
if(parameters[i] is Array) paramsToSend[i] = parameters[i];
else paramsToSend[i] = parameters[i].toString();
}
}
return paramsToSend;
}
The flashVars variable is the one that should contain the values from the HTML file. But whenever I run the program and output the variables in the PHP file I receive the following.
//Using this command on the PHP page
print_r($_POST);
//I get this for output
Array
(
[Filename] => testfile.txt
[Upload] => Submit Query
)
Its almost like the parameters are getting over written or are just not working at all.
Thanks for any help,
Metropolis
Try...
print_r($_FILES);
Like I said in my comment: Do you successfully receive the variable in Flash from the flashvars?
I haven't done Flash in a while but maybe, instead of your objectToURLVariables function, just referencing each variable directly is a better way. At least to figure out if you have those variables from your HTML page. So maybe do something like this:
var myVar:String = LoaderInfo(this.root.loaderInfo).parameters.myVar;
var flashVars:URLVariables = objectToURLVariables(myVar);
Ok, I have fixed the issue somehow.....I kept changing things back and forth and realized that the cache had not been cleared in awhile. I cleared the cache and it started working for some reason.
I did change one line back to the way I had it before.
I changed
var flashVars:URLVariables = objectToURLVariables(this.root.loaderInfo);
To
var flashVars:URLVariables = objectToURLVariables(root.loaderInfo.parameters);
Im not positive that this was causing the problem. It may have been that I just needed to clear the cache the whole time. Anyway, thanks for your help guys.

Categories