Hello i am new to the flash . Just i want to how to pass values from Flash variable to php
i am using this code
var myVars:LoadVars = new LoadVars();
myVars.playerName = "Some Body";
myVars.playerTime = Timer;
myVars.send("index.html", "_parent", "POST");`
it show error - >
Warning: 1060: Migration issue: The method LoadVars is no longer supported. For more information, see the URLVariables class, the URLRequest.urlVariables and URLRequest.postData properties, and the URLLoader.dataFormat property..
please guide me how do i resolve this error . i am using CS4 for flash and AS3.0
LoadVars() is AS2 only. You need to use URLLoader. Try this class:
package
{
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.net.URLVariables;
import flash.net.URLRequestMethod;
import flash.events.Event;
/**
* #author Marty Wallace
* #version 1.00
*/
public class PHPData extends Object
{
/**
* Sends data to a PHP script
* #param script A URL to the PHP script
*/
public function send(script:String, vars:URLVariables):void
{
var req:URLRequest = new URLRequest(script);
req.data = vars;
req.method = URLRequestMethod.POST;
var loader:URLLoader = new URLLoader();
loader.load(req);
// listeners
loader.addEventListener(Event.COMPLETE, _complete);
}
/**
* Called when a response has been received from a PHP script
* #param e Event.COMPLETE
*/
private function _complete(e:Event):void
{
var vars:URLVariables = new URLVariables(e.target.data);
var i:String;
for(i in vars)
{
trace(i + ": " + vars[i]);
}
e.target.removeEventListener(Event.COMPLETE, _complete);
}
}
}
Then you can do what you're doing like so:
var php:PHPData = new PHPData();
var vars:URLVariables = new URLVariables();
vars.playerName = "Some Body";
vars.playerTime = Timer;
php.send("index.php", vars);
Another thing I noticed was you're using send to send data to a .html document rather than a .php document..
A small tutorial on creating this class to use (based on comments):
Click File -> New -> ActionScript file.
Paste the above package (first chunk of code) into the new file.
Save the file in the same directory as your .fla file.
Paste my second snippet of code into the timeline of your .fla file.
All should work from here.
Here is a .zip containing an example you can use.
http://junk.projectavian.com?f=phpdata.zip
Related
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLLoaderDataFormat;
import flash.net.URLVariables;
public class registration extends MovieClip {
public function registration() {
regbtn.addEventListener(MouseEvent.MOUSE_DOWN, checkForm);
MovieClip(root).reguser.text = "";
MovieClip(root).regpass.text = "";
}
function checkForm (e:MouseEvent):void {
if (MovieClip(root).reguser.text != "" && MovieClip(root).regpass.text != "") {
sendForm();
}else{
regerr.text = "Please fill in all the fields!";
}
}
function sendForm ():void {
**/*
we use the URLVariables class to store our php variables
*/**
var phpVars:URLVariables = new URLVariables();
phpVars.username = reguser.text;
phpVars.password = regpass.text;
**/*
we use the URLRequest method to get the address of our php file and attach the php vars.
*/**
var urlRequest:URLRequest = new URLRequest("http://localhost/accounts/regdb.php");
**/*
this attaches our php variables to the url request
*/**
urlRequest.data = phpVars;
**/*
the POST method is used here so we can use php's $_POST function in order to recieve our php variables.
*/**
urlRequest.method = URLRequestMethod.POST;
**/*
we use the URLLoader class to send the request URLVariables to the php file
*/**
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
**/*
runs the function once the php file has spoken to flash
*/**
urlLoader.addEventListener(Event.COMPLETE, showResultreg);
**/*
we send the request to the php file
*/**
urlLoader.load(urlRequest);
}
**/*
function to show result
*/**
function showResultreg (e:Event):void {
regerr.text = "" + e.target.data.result_message;
}
}
}**
ERROR
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 recently started delving into custom classes in AS3 (to hone my best-practices coding habits), and wanted to create a database class that allows a user to first instantiate a class that contains all the information necessary for methods within the class to add, delete, modify (etc) rows in a MySQL table (via PHP). Of course, this involves using URLRequest, URLLoader and so forth. My question is whether anyone as figured a way how to return data from a method specifically containing that var data without relying upon the method essentially dispatching an event (then having to create a listener rather than having that built into the class). For example,
var myDB:dataBase = new dataBase("dbase","table","username","pword");
//this creates an instance of a database class with methods like:
trace(myDB.fetch(1)); //gets first row of table as a delimited string
OR
if (myDB.delete(1)) {}
//returns Boolean true if delete of row 1 was successful
I found the answer below that contained a way to create a class that returns an event:
Combining URLRequest, URLLoader and Complete Event Listener In Actionscript 3.0?
but I want the method to return a string containing data from the database or a boolean confirmation, not to dispatch an event listener. Here is an example of the class I made:
package com.customClasses {
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequestMethod;
import fl.events.DataChangeEvent;
import flash.events.Event
public class dataBase {
public var dbs:String = "";
public var usr:String = "";
public var pwd:String = "";
public var tab:String = "";
var returnData:String = "";
// Constructor
public function dataBase(dbs:String, usr:String, pwd:String, tab:String) {
this.dbs = dbs;
this.usr = usr;
this.pwd = pwd;
this.tab = tab;
}
public function fetch(idn:uint, par:String):String {
var returnData:String = "blank";
var vUrlReq:URLRequest = new URLRequest ("dBase.php");
var vUrlVars:URLVariables = new URLVariables();
function onLoadVarsComplete(event:Event): void {
//retrieve success variable from our PHP script:
if(event.target.data.msg == "success") {
var rawData:URLVariables = new URLVariables( event.target.data );
returnData = rawData.fromPHP;
} else {
returnData = "failed!";
}
}
vUrlReq.method = URLRequestMethod.POST;
vUrlVars.dir=dbs; // name of table affected
vUrlVars.alpha=usr; // username
vUrlVars.beta=pwd; // password
vUrlVars.dbase=tab; // name of table affected
vUrlVars.func="fetch"; // function for php script to use
vUrlVars.idnum=idn; //if >0 search for record with that id
vUrlReq.data = vUrlVars;
var vLoader:URLLoader = new URLLoader (vUrlReq);
vLoader.addEventListener("complete", onLoadVarsComplete);
vLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
vLoader.load(vUrlReq);
return (returnData);
}
returnData returns "blank"... so I realize my method is not working as intended. I also realize there my be some scope issues with the returnData string, and that I am using a nested function (probably a no-no). Otherwise, any thoughts?
To do what you want, you can use a callback function or a DataEvent listener, like this :
DB.as :
package {
import flash.net.*;
import flash.events.*;
public class DB extends EventDispatcher {
public static const DATA_LOADED = 'data_loaded';
public function DB() {
}
public function getDataUsingDataEvent(file_path:String):void {
var url_loader:URLLoader = new URLLoader();
url_loader.addEventListener(
Event.COMPLETE,
function(e:Event):void
{
var event:DataEvent = new DataEvent(DATA_LOADED, true, false, url_loader.data);
dispatchEvent(event);
}
)
url_loader.load(new URLRequest(file_path));
}
public function getDataUsingCallback(file_path:String, callback:Function):void {
var url_loader:URLLoader = new URLLoader();
url_loader.addEventListener(
Event.COMPLETE,
function(e:Event):void
{
callback(url_loader.data);
}
)
url_loader.load(new URLRequest(file_path));
}
}
}
And then :
var db:DB = new DB();
db.addEventListener(
DB.DATA_LOADED,
function(event:DataEvent):void {
trace(event.data);
}
)
db.getDataUsingDataEvent('file_path');
db.getDataUsingCallback(
'file_path',
function(data:String):void {
trace(data);
}
)
Hope that can help.
As you've stated it, this can't be done in AS3. You cannot wait for an asynchronous operation (such as URLLoader/load()) before returning the function and continuing script execution.
What you can do, if you'd prefer not to use addEventListener() so much, is pass through callbacks, or implement method chaining of promises. These patterns are not necessarily better than using events, and have their own problems, but let you write code that is arguably more readable as a sequence. These patterns are common in Javascript (which has the same asynchronous behavior as ActionScript), for example jQuery. Beware of "callback hell" and "train wrecks". These techniques aim to make things simpler to write but sometimes make things more error prone.
I'm using the following code to check for updates in mysql database using flash as3 (actionscript 3.0).
The code will check the database using PHP on my server and will display the details in Flash application.
The issue that I have is that I am trying to run this code every 8 seconds but when I run the code and I trace(urlRequest); I get 100's of traces in less than 20 seconds!
I thought giving a setInterval(checkDataBase, 8000); will sort this issue out and will run the code every 8 seconds but I have no luck with this!
Could someone please advise on this issue?
This is my code:
addEventListener(Event.ENTER_FRAME,checkForNewOrder);
function checkForNewOrder (e:Event):void
{
checkDataBase();
}
/*
function we use to send the form
*/
function checkDataBase ():void
{
/*
we use the URLVariables class to store our php variables
*/
var phpVars:URLVariables = new URLVariables();
phpVars.result_textL = result_textL.text;
/*
we use the URLRequest method to get the address of our php file and attach the php vars.
*/
var urlRequest:URLRequest = new URLRequest("http://mywebsite.com/checkOrder.php");
trace(urlRequest);
/*
the POST method is used here so we can use php's $_POST function in order to recieve our php variables.
*/
urlRequest.method = URLRequestMethod.POST;
/*
this attaches our php variables to the url request
*/
urlRequest.data = phpVars;
/*
we use the URLLoader class to send the request URLVariables to the php file
*/
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
/*
runs the function once the php file has spoken to flash
*/
urlLoader.addEventListener(Event.COMPLETE, showResult);
/*
we send the request to the php file
*/
urlLoader.load(urlRequest);
}
setInterval(checkDataBase, 8000);
/*
function to show result
*/
function showResult (e:Event):void
{
orderDetails.text = "" + e.target.data.result_message;
if(orderDetails.text != "")
{
rejectBtn.y = 380.20;
}
}
addEventListener(Event.ENTER_FRAME,checkForNewOrder);
This causes your function to be called with the framerate you set up, so mabye 30 times per second.
setIntervall will add additional calls to the function. It does not override the enter frame.
Get rid of the enter frame register and you should be good to go.
I am trying to make a simple Flash ActionScript3 program that saves some text to a text file (on my server) via a PHP script. I want the Flash program to be able to detect if the PHP script fails to write. Right now I'm just trying to get Flash to trace a status received from PHP. My below code is based on a few examples I've found online.
Here is my Flash code:
import flash.net.*;
import flash.events.*;
var varLoader:URLLoader = new URLLoader;
var varURL:URLRequest = new URLRequest("http://xxxxxxxx/outputTest.php");
var submittedData:URLVariables=new URLVariables();
varURL.data = submittedData;
varURL.method = URLRequestMethod.POST;
submittedData.inputData = "ThisIsTheDataToBeSaved";
submittedData.FileName = "ThisIsTheFileName";
varLoader.addEventListener(Event.COMPLETE, fxnDoneSaving);
varLoader.load(varURL);
function fxnDoneSaving(evt:Event):void{
trace("Done saving.");
trace("Write status: "+String(evt.target.data.WasWritingSuccessful));
}
Here is my PHP code:
<?php
$receivedFromFlashData = $_POST['inputData'];
$receivedFromFlashFileName = $_POST['FileName'];
$filename = $receivedFromFlashFileName . ".txt";
$myTextFileHandler = fopen($filename,"w");
if($myTextFileHandler)
{$writeInTxtFile = #fwrite($myTextFileHandler,"$receivedFromFlashData");}
fclose($myTextFileHandler);
if ($writeInTxtFile)
{echo "WasWritingSuccessful=success";}
else
{echo "WasWritingSuccessful=failure";}
?>
When Flash gets to the final trace statement, I get the following error:
"ReferenceError: Error #1069: Property WasWritingSuccessful not found on String and there is no default value."
Please help me understand what I'm doing wrong? thanks!
You need to specify the dataFormat of varLoader like so: varLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
I'm using Ming to create an library swf, using the first code example below. How can I access the embedded png from my Flex application? Here's the php/ming code:
<?php
// Ming to create Library.swf
//-----------------------------------
// Create background...
Ming_setScale(20.0000000);
$movie = new SWFMovie();
ming_useswfversion(7);
$movie->setDimension(550,400);
$movie->setBackground(200, 200, 200);
// Load png file...
$img_file = "src/assets/page0.png";
$png = new SWFBitmap(fopen($img_file, "rb"));
// Add png to movie...
$movie->add($png);
// Export png
$movie->addExport($png, 'png');
$movie->writeExports();
// Save movie to swf
$swfname = dirname(__FILE__);
$swfname .= "/bin-debug/Library.swf";
$movie->save($swfname, 9);
?>
And here's my flex essay:
// Loading Library.swf (works), trying to access png asset (doesn't work)
private var loader:Loader = new Loader();
private function onCreationComplete():void {
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
loader.load(new URLRequest('Library.swf'));
}
private function onComplete(e:Event):void {
var resourceClass:Class = loader.contentLoaderInfo.applicationDomain.getDefinition("png") as Class;
}
I'm not sure that the png is exported properly. Testing the Library.swf with SwfUtils code (swfutils.riaforge.org) doesn't show any exported classes at all. Or maybe something else is wrong?
well I have the same problem
I create a library with ming and try to access it from flex and doesn't work.
I've only used this because I needed somehow for an certain url using the Loader class to retrieve the Class object that I can use it to set backgroundImage for a Canvas for example.
But I think that swf exported by ming my have a lower version than the flex compiled swf, and it can't recognize the embedded class name unfortunately.
You need to use assignSymbol function within code.
#!/usr/bin/ruby
require 'ming/ming'
include Ming
use_SWF_version(9)
set_scale(20.00000000)
#m = SWFMovie.new
#m.set_dimension(640, 480)
#bm = SWFBitmap.new("./common/MatrixFilter.jpg")
#m.add(#bm)
#text = SWFText.new
#font = SWFFont.new("./common/test.ttf")
#text.set_font(#font)
#text.set_color(0, 0, 0, 0xff)
#text.set_height(20)
#text.move_to(100, 100)
#text.add_string( "The quick brown fox jumps over the lazy dog. 1234567890")
#i1 = #m.add(#text)
#i1.set_depth(1)
#m.next_frame
#m.assign_symbol(#text, "mytext")
#m.assign_symbol(#bm,"mybitmap")
#m.save("assignSymbol.swf")
Then use something like this in Flex: (FlashDevelop project)
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.Bitmap;
import flash.events.Event;
/**
* ...
* #author DefaultUser (Tools -> Custom Arguments...)
*/
public class Main extends Sprite
{
[Embed(source="my_clip.swf", symbol="circle")]
private static var Circle:Class;
[Embed(source="App.swf", symbol="star")]
private static var Star:Class;
[Embed(source="App.swf", symbol="square")]
private static var Square:Class;
[Embed(source = 'assignSymbol.swf', symbol = 'mytext')]
private static var Mytext:Class;
[Embed(source='assignSymbol.swf', symbol='mybitmap')]
private static var Mybitmap:Class;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
var circle:Sprite = new Circle();
addChild(circle);
circle.x = 100;
circle.y = 100;
var star:Sprite = new Star();
addChild(star);
star.x = 200;
star.y = 100;
var square:Sprite = new Square();
addChild(square);
square.x = 300;
square.y = 100;
var mybitmap:Bitmap = new Mybitmap();
addChild(mybitmap);
mybitmap.x = 300;
mybitmap.y = 300;
var mytext:Sprite = new Mytext();
addChild(mytext);
mytext.x = 0;
mytext.y = 200;
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
}
}
}