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.*;
Related
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.
I have used ShineMP3 to record sound. Now I'm trying to upload the mp3 file to server. Here is my AS3 code:
function onWavClick(e:MouseEvent)
{
var sba:ByteArray = mp3Encoder.mp3Data;
var req:URLRequest = new URLRequest('http://localhost/upload.php');
req.contentType = 'application/octet-stream';
req.method = URLRequestMethod.POST;
req.data = sba;
var loader:URLLoader = new URLLoader(req);
}
How can I display a percentage of upload, and if it was complete and successfully go to next frame?
Thanks.
Instead of passing the URLRequest in the constructor of your URLLoader, use the URLLoader's load() method. There really is no occasion you should pass the request through the constructor, as it starts the request immediately and can complete before you are able to attach an event listener at times. Always follow this process:
Instantiate URLLoader and URLRequest
Attach event listeners and set properties on both
Call load() using the URLRequest
This will allow you to attach a ProgressEvent event of type PROGRESS, which will include a bytesTotal and a bytesLoaded property when it is dispatched. You can use these to display the percentage however you want. You can also attach Event.COMPLETE, which will fire when the upload is finished.
function onWavClick(e:MouseEvent)
{
var sba:ByteArray = mp3Encoder.mp3Data;
var req:URLRequest = new URLRequest(URL);
req.contentType = 'application/octet-stream';
req.method = URLRequestMethod.POST;
req.data = sba;
var loader:URLLoader = new URLLoader();
loader.addEventListener( ProgressEvent.PROGRESS, progressHandler );
loader.addEventListener( Event.COMPLETE, completeHandler );
loader.load( req );
}
function progressHandler( e:ProgressEvent ):void {
trace( e.bytesLoaded / e.bytesTotal ); // output: progress, as a decimal from 0 to 1
}
function completeHandler( Event ):void {
// download/upload is complete
}
One suggestion could be this PHP Upload Progress bar:
http://www.johnboyproductions.com/php-upload-progress-bar/
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
Θ)
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! ;)
is it possible to call a PHP function from flash and have it execute right away?
If so how could I go about doing that, because I am trying to call a PHP function that will update a users facebook status, but thus far I have been unsuccessful, so I am kind of at the end f my rope.
Any help would be appreciated, thanx!
My idea would be something similar to the following:
function updateFBStatus(newStatus)
{
// create two new instances of LoadVars, one to send and one to receive data
var dataOut:LoadVars = new LoadVars();
var dataIn:LoadVars = new LoadVars();
// define what should happen when the response is received,
// using 'this' to refer to dataIn and get data from it
dataIn.onLoad = onReturn;
dataOut["newStatus"] = newStatus;
dataOut.sendAndLoad(serverURL+"setFBStatus.php", dataIn, "POST");
}
You then define the setFBStatus.php file on your server to read $_POST['newStatus'] and do whatever you would normally do in php to set the facebook status. That php file can optionally echo some return values in url request format (i.e, paramName1=param1¶mName2=param2&) for your onReturn function to read, if you need to.
Have a look at AMF PHP!
Save the PHP function in facebookFunction.php and call it using a URLLoader.
var urlLoader:URLLoader = new URLLoader();
var data:URLVariables = new URLVariables();
//you can use dot syntax and/or [] syntax to add data.
data.user = "kiele";
data["someThingElse"] = "something else";
var req:URLRequest = new URLRequest("facebookFunction.php");
req.data = data;
urlLoader.load(req);
At the php side, you can read the values from the global get variable.
$user = $_GET["user"]
The way I would do it is in the flash actionscript is call a javascript function using getURL("javascript:someFunction(var-1, var-2, var-n)") http://www.adobe.com/livedocs/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001180.html
That javascript function can then do an ajax request to a php script.
EDIT:
you could just post data directly without using AJAX:
var firstName:String = "Gus";
var lastName:String = "Richardson";
var age:Number = 92;
getURL("http://www.adobe.com", "_blank", "POST");
Why you are not using a Flash API for Facebook: http://code.google.com/p/facebook-actionscript-api/ ?