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;
Related
I'm currently having a bit of an issue when I try to upload a photo taking using an iOS camera to a MySQL database using PHP and unfortunately have been unable to find the right help online.
Basically The User takes a photo on their iOS device and I take that raw MediaPromise and put it into a ByteArray. I then call a PHP function using AMFPHP to add the binary to a Blob in my database. But when I test the whole thing, it never seems to work. Could somebody maybe help me with this problem or at least point me in the right direction? It would be highly appreciated. Here's the code:
AS3:
var dataSource:IDataInput;
function imageSelected1(event:MediaEvent) {
var imagePromise:MediaPromise = event.data;
dataSource = imagePromise.open();
if( imagePromise.isAsync ) {
var eventSource:IEventDispatcher = dataSource as IEventDispatcher;
eventSource.addEventListener( Event.COMPLETE, onDataComplete );
}
else {
readMediaData();
}
}
// PHP Connection //
// Database //
var gw2:NetConnection = new NetConnection();
gw2.connect(connectiongoeshere);
// Responder //
var pictureresponder:Responder = new Responder(onpicture);
function onpicture(pictureobj:Object) {
gotoAndStop(1);
}
function onDataComplete( event:Event ):void {
readMediaData();
}
function readMediaData() {
var imageBytes:ByteArray = new ByteArray();
//dataSource.readBytes( imageBytes );
dataSource.readBytes(imageBytes);
gw2.call("class.setData", pictureresponder, imageBytes);
}
PHP:
function setData($ba) {
// Connecting to the database //
mysql_pconnect("hi", "hi", "hi");
mysql_select_db("hi");
$result = mysql_query("UPDATE users set profilepicture2 ='$ba->data' WHERE email= 'email#gmail.com'");
return $result;
}
I have been following a flash tutorial online and I have created a simple flash interface. I am trying to retrieve data from my SQL database via a PHP file and display. I get the following error when I compile:
Error #1009: Cannot access a property or method of a null object reference
var variables1:URLVariables = new URLVariables();
var varSend1:URLRequest = new URLRequest("databaseCall.php");
varSend1.method = URLRequestMethod.POST;
varSend1.data = variables1;
var varLoader1:URLLoader=new URLLoader();
varLoader1.dataFormat = URLLoaderDataFormat.VARIABLES;
varLoader1.addEventListener(Event.COMPLETE,completeHandler1);
variables1.comType = "requestEntries";
varLoader1.load(varSend1);
function completeHandler1(event:Event):void{
if(event.target.data.returnBody ==""){
gbOutput_txt.text = "No data coming through";
} else{
gbOutput_txt.condenseWhite = true;
gbOutput_txt.htmlText = "" +event.target.data.returnBody;
}
}
My code exactly matches the code that is used within the tutorial. I have modified the php file to simply return "" so the issue almost definitely lies within the action script...I think :S The compiler falls over when he completeHandler1 function is called. What do you think could be causing this?
Thanks in advance.
You need to declare the completeHandler1 function before you attempt to use it anywhere else.
Here is your code modified to describe what I am talking about.
var variables1:URLVariables = new URLVariables();
var varSend1:URLRequest = new URLRequest("databaseCall.php");
varSend1.method = URLRequestMethod.POST;
varSend1.data = variables1;
function completeHandler1(event:Event):void{
if(event.target.data.returnBody ==""){
gbOutput_txt.text = "No data coming through";
} else{
gbOutput_txt.condenseWhite = true;
gbOutput_txt.htmlText = "" +event.target.data.returnBody;
}
}
var varLoader1:URLLoader=new URLLoader();
varLoader1.dataFormat = URLLoaderDataFormat.VARIABLES;
varLoader1.addEventListener(Event.COMPLETE,completeHandler1);
variables1.comType = "requestEntries";
varLoader1.load(varSend1);
Give this a try and let me know if it works.
I want to create a login database in Flash via MySQL PHP route. I copied a large portion of the code from some tutorials. My login basically contains users entering their email address picking a password and I have a basic Combobox.
When I run the code I receive this error...
ReferenceError: Error #1069: Property data not found fl.controls.Button and there is no default value.
at phpRegister_fla::MainTimeline/btnHandler()
I have debugged Flash but I don't get any additional information.
After searching online I still don't understand what is causing the error.
I hope my code will help you pinpoint where I am going wrong. Apologies its kind of long.
Any help much appreciated.
import flash.net.URLVariables;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.events.Event;
import flash.text.TextField;
import fl.data.DataProvider;
import fl.controls.Button;
btn_Submit.addEventListener(MouseEvent.CLICK, btnHandler);
//Validate form fields
function btnHandler(event:MouseEvent):void {
status_Txt.text = "" + event.target.data.systemResult;
trace(event.target.data.systemResult);
var phpVars:URLVariables = new URLVariables();
var phpFileRequest:URLRequest = new URLRequest("phpFile");
phpFileRequest.method = URLRequestMethod.POST;
phpFileRequest.data = phpVars;
phpVars.email = email.text;
phpVars.ps_wd = ps_wd.text;
var phpLoader:URLLoader = new URLLoader();
phpLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
}
textOneField.addEventListener(Event.CHANGE, changeHandler);
function changeHandler(event:Event):void {
trace("data entered");
}
textTwoField.addEventListener(Event.CHANGE, changeData);
function changeData(event:Event):void {
trace("data changed");
}
email.addEventListener(KeyboardEvent.KEY_UP, keyHandler);
ps_wd.addEventListener(KeyboardEvent.KEY_UP, keyEnter);
function keyHandler(event:KeyboardEvent):void {
if(event.keyCode == Keyboard.ENTER)
trace("keyboard was pressed");
}
function keyEnter(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.ENTER)
trace("Enter button hit");
}
var persons:Array = new Array();
persons[0] = "Male";
persons[1] = "Female";
c_two.dataProvider = new DataProvider(persons);
c_two.addEventListener(Event.CHANGE, dataHandler);
function dataHandler(event:Event):void {
trace(event.target.value);
}
There probably isn't anything wrong with the code. It is rather that you are using a component that doesn't exist in the "standard flash library" namely fl.controls.button. In order for you to be able to use that you need to add a linkage to that component.
Since you didn't mention how you compile your code it is kinda hard to tell you what to do. However, you probably don't need the fl-button but could do with a "SimpleButton" or "Movieclip" or something else instead.
If Flash:
http://forums.adobe.com/message/4260710?tstart=0
Similar issue:
AS3 Error: '1172: Definition fl.controls:Button could not be found.'
More info:
http://www.actionscript-flash-guru.com/blog/14-flcontrols-not-found-how-do-i-import-the-fl-package
In your btnHandler function you have :
... event.target.data.systemResult ...
Where event.target seem to be an fl.control.Button object.
Those objects have no "data" property.
i don't know what you are looking for in event.target.data.systemResult ?
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
I am trying to upload image files to my server using AS3 and PHP, and at the moment I am succeeding in uploading multiple files and restricting it to images only, but since I am new to Flash and AS3, I am finding it difficult to figure out how to have a loader bar show when the files are being uploaded, as well as executing a function once all files have been uploaded to go to a specified frame.
Here is my code thus far,
AS3:
import flash.net.FileReferenceList;
import flash.events.Event;
import flash.net.URLRequest;
import flash.net.FileReference;
var fileRef:FileReferenceList = new FileReferenceList();
fileRef = new FileReferenceList();
fileRef.browse(new Array( new FileFilter( "Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png" )));
fileRef.addEventListener(Event.SELECT, fileSelectHandler);
var uploadURL:URLRequest = new URLRequest();
var uploadPhotoScript:String = "http://127.0.0.1/upload.php";
uploadURL.url = uploadPhotoScript;
function fileSelectHandler(event:Event):void {
for each(var fileToUpload:FileReference in fileRef.fileList){
uploadSingleFile(fileToUpload);
}
}
function uploadSingleFile(file:FileReference):void {
file.upload(uploadURL);
file.addEventListener(Event.COMPLETE, completeHandler);
}
function completeHandler(event:Event):void {
trace("upload complete");
}
PHP:
if(!empty($_FILES)){
$tmpfile = $_FILES['Filedata']['tmp_name'];
$targetfile = dirname(__FILE__) . '/' . $_FILES['Filedata']['name'];
move_uploaded_file($tmpfile, $targetfile);
}
my questions are,
1: how can I display a percentage or a uploading bar indicating the progress of the files being uploaded?
2: How can I launch a callback function after ALL files have been uploaded successfully?
3: How can I make the file browser appear on click, and not upon loading the flash file?
If you guys could post a link or two to good tutorials/resources or some advice, maybe even a code snippet or two that would be a great help as I am very new to Actionscript 3.
Thanx in advance!
To answer your questions in sequence:
1: You can use the ProgressEvent to display file upload progress. Since the File will be the dispatcher of the event, you can access the FileReference that has dispatched the progress as e.currentTarget inside the event, and from here you can access the unique properties of that file reference so you can accurately update the visual upload progress for that specific file. For example:
function uploadSingleFile(file:FileReference):void {
file.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
file.upload(uploadURL);
file.addEventListener(Event.COMPLETE, completeHandler);
}
function onUploadProgress(e:ProgressEvent):void
{
var f:FileReference = e.currentTarget as FileReference;
var fileName:String = f.name; //Now I know which file it is, I can update accordingly
var progress:Number = (e.bytesLoaded / e.bytesTotal) * 100; //shows percent, you might want to round this off using Math.round(number);
}
2: In order to launch a callback after ALL files are loaded, you'd do this by storing the number of files initially selected, then adding a callback specifically to each item and as they complete, decrement the total count until it is 0, at which time you'll know all files have been uploaded:
var totalFiles:int = 0;
function fileSelectHandler(event:Event):void {
for each(var fileToUpload:FileReference in fileRef.fileList){
++totalFiles;
uploadSingleFile(fileToUpload);
}
}
function uploadSingleFile(file:FileReference):void {
file.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
file.addEventListener(Event.COMPLETE, onFileUploadComplete);
file.upload(uploadURL);
file.addEventListener(Event.COMPLETE, completeHandler);
}
function onFileUploadComplete(e:Event):void
{
--totalFiles;
if(totalFiles == 0){
//All files have been uploaded
}
}
3: To make the browser appear onClick, simply add a MouseEvent.MOUSE_DOWN listener to an object or button of some kind, or even the stage, whatever. Like so:
var uploadButton:Button = new Button(); // Note this will require the Button component to be included in your library in flash CS
uploadButton.label = "Upload Files";
uploadButton.width = 150; //Or whatever;
uploadButton.x = (stage.stageWidth * .5) - (uploadButton.width * .5);
uploadButton.y = (stage.stageHeight * .5) - (uploadButton.height * .5);
stage.addChild(uploadButton);
uploadButton.addEventListener(MouseEvent.MOUSE_DOWN, onUploadClicked);
function onUploadClicked(e:MouseEvent):void
{
var fileRef:FileReferenceList = new FileReferenceList();
fileRef = new FileReferenceList();
fileRef.browse(new Array( new FileFilter( "Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png" )));
fileRef.addEventListener(Event.SELECT, fileSelectHandler);
}
And finally about the tutorials etc, I'd recommend http://gotoandlearn.com for learning flash. I would also recommend just checking out the AS3 docs, as all of this nfo can be gleaned from just looking up the class in question, FileReferenceList. Please note I've done this code off of the top of my head in here so I had no IDE checking or anything. However it should work just fine. Hope this helps. :)
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReferenceList.html
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html#upload()
http://adobe.com/go/as3lr