Actionscript multiple file upload, with parameter passing is not working - php

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.

Related

echo not returning variable value on php actionscript connection

I'm trying to pass some variables from php to flash, im using this actionscript code:
public function gameOver(score:Number)
{
totalScore.text = score.toString();
var scriptVars:URLVariables = new URLVariables();
scriptVars.score = score;
var scriptLoader:URLLoader = new URLLoader();
var scriptRequest:URLRequest = new URLRequest("checkScores.php");
scriptRequest.method = URLRequestMethod.POST;
scriptRequest.data = scriptVars;
scriptLoader.load(scriptRequest);
scriptLoader.addEventListener(Event.COMPLETE, handleLoadSuccessful);
scriptLoader.addEventListener(IOErrorEvent.IO_ERROR, handleLoadError);
}
function handleLoadSuccessful(e:Event):void
{
trace("Scores Loaded");
var vars:URLVariables = new URLVariables(e.target.data);
nickname1.text = vars.nickname;
score1.text = vars.score;
}
function handleLoadError($evt:IOErrorEvent):void
{
trace("Load failed.");
nickname1.text ="error";
}
And this php code:
<?php
... some code for the mysql connection and select sentence ...
$topScores = mysqli_query($con, $topScores);
$topScores = mysqli_fetch_array($topScores);
echo "&nickname=$topScores[nickname]&score=$topScores[score]";
?>
both runs without errors, the problem is that what i get on flash aren't the variables values but the name of the variables, in other words what i get on vars.nickname is
$topScores[nickname]
and for vars.score
$topScores[score]
If i run the php alone i get this:
&nickname=jonny&score=100
which are the actual variable values i'm trying to get, any help would be greatly appreciated.
I think you may just be loading up the php file as a text file from flash. Can you change the following line:
new URLRequest("checkScores.php");
to something like:
new URLRequest("http://localhost/checkScores.php");
or whatever you see in the browser address bar when you "run" it as you said in your question.

How to Get Array From URL Encoded String?

I'm sure this is a very easy thing but I couldn't find it in google for hours.
I'm new to ActionScript and I'm trying to obtain an array of variables from a string that is generated by a .php file.
my php file outputs this:
var1=42&var2=6&var3=string
And my ActionScript code is:
public function CallAjax_VARIABLES(url:String , the_array:Array)
{
var request:URLRequest = new URLRequest(url);
var variables:URLLoader = new URLLoader();
variables.dataFormat = URLLoaderDataFormat.VARIABLES;
variables.addEventListener(Event.COMPLETE, VARIABLES_Complete_Handler(the_array));
try
{
variables.load(request);
}
catch (error:Error)
{
trace("Unable to load URL: " + error);
}
}
function VARIABLES_Complete_Handler(the_array:Array):Function {
return function(event:Event):void {
var loader:URLLoader = URLLoader(event.target);
//the_array = loader.data; // this doesn't work.
//the_array = URLVariables.decode(loader); // this doesn't work either.
//trace(loader.data['var1']); // this outputs 42, so I'm getting the string from php.
};
}
I think you already understood this but, in the end, I want to have an array (In ActionScript) that will give me:
the_array['var1']=42;
the_array['var2']=6;
the_array['var3']="string";
What am I doing wrong? What should I do?
Thanks!
EDIT:
I'm trying to get variables FROM php TO ActionScript.
e.g. My PHP file correctly converts the array to an html query, But I don't know how to parse them in an array in ActionScript.
You should use URLVariables for this.
var vars:URLVariables = new URLVariables(e.target.data);
This way you can simply say:
trace(vars.var2); // 6
An array would be useless here as the result is associative rather than index based, though you can easily take all the values and throw them into an array with a simple loop:
var array:Array = [];
for(var i:String in vars)
{
array.push(vars[i]);
}
I think you are looking for parse_str function
parse_str($str, $output);
Sorry, I thought this was a PHP question. In ActionScript, try this:
var the_array:URLVariables = new URLVariables();
the_array.decode(loader.data);
trace(the_array.var1);

ActionScript - Contact Form Not Working

I'm trying to debug a contact form that was built in Flash, but I'm not sure how I can go about debugging this. From the ActionScript, I can tell that it's supposed to POST the results to /assets/files/functions.php. The problem is that when I fill out the fields and click onto 'Send' (which is supposed to trigger this), nothing happens and I can't tell if it's a PHP issue or a flash issue.
Is there any ideas as to how to debug this?
The website can be found here and the form can be seen by clicking onto 'Connect' and then click onto 'Send Inquiry'.
The code may be seen below:
lvOut = new LoadVars(); //create lv object
lvIn = new LoadVars(); //create lv object
lvIn.onLoad = function (success) {
if(success){
gotoAndPlay("success");
}else{
gotoAndPlay("failure");
}
}
function submit() {
if ( (inputName.text != "") && (inputAddress.text != "") && (inputCity.text != "") && (inputState.text != "")
&& (inputCountry.text != "") && (inputTelephone.text != "") && (inputEmail.text != "") ) {
lvOut.input_name = inputName.text;
lvOut.input_address = inputAddress.text;
lvOut.input_city = inputCity.text;
lvOut.input_state = inputState.text;
lvOut.input_zip = inputZip.text;
lvOut.input_country = inputCountry.text;
lvOut.input_telephone = inputTelephone.text;
lvOut.input_email = inputEmail.text;
lvOut.input_bedrooms = inputBedrooms.text;
lvOut.input_realtor = inputRealtor.text;
lvOut.input_comments = inputComments.text;
if (realtorYes) {
lvOut.input_hasRealtor = "yes";
} else if (realtorNo) {
lvOut.input_hasRealtor = "no";
} else {
lvOut.input_hasRealtor = "no answer";
}
//send vars to functions page and load in result
lvOut.sendAndLoad("assets/files/functions.php", lvIn, "POST");
}
}
btnSend.addEventListener("click", submit);
Please help me out as much as possible! :-)
You have a problem in your flash app: it sends nothing. I just entered webpage you said with Chrome and opened "Network" tab in "Developer's tools" menu. It captured 0 requests on "send" button click. I don't know AS2 (saveAndLoad is AS2 method), so I can't say what is wrong, but here
is a working example of POST request in AS3.
Try taking a different approach by using URLLoader class. I assume your functions.php file is somewhere online.
const SITE_DOMAIN:String = "PUT_YOUR_SITE_DOMAIN_HERE_UP_TO_ASSETS_FOLDER";
var loader = new URLLoader();
loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
loader.addEventListener(Event.COMPLETE, loadCompleteHandler);
request = new URLRequest();
request.url = SITE_DOMAIN + "assets/files/functions.php";
request.method = URLRequestMethod.POST;
loader.load(request);
function loadCompleteHandler(event:Event):void
{
// handle load complete
}
function securityErrorHandler(event:SecurityErrorEvent):void
{
// handle security error
}
function ioErrorHandler(event:IOErrorEvent):void
{
// handle io error
}
Hope this help.
You have an error in your PHP script : http://nordicacondos.com/assets/files/functions.php
Fix it, then try some trace in your AS code to see what is send to PHP.
Check if your test on non empty values works by adding a trace inside (I think your problem is here because your swf sends nothing even if all fields are filled)
Check the content of the lvOut object before send, in AS2 you can browse the content like this
for (var name in lvOut) {
trace(name +'->' + lvOut[name]);
}
Add the full path to the PHP script so you can test from Flash IDE.
Add a trace in the lvIn onLoad handler to check if its fired
You may also check on the PHP side by logging the raw request like this :
$handle = fopen('log.txt', 'ab+');
fwrite($handle, print_r($_REQUEST, true) );
fwrite($handle, PHP_EOL);
fclose($handle);
Make sure that you have write permissions on the functions.php directory.
Of course using AS3 would offer better control... :)

Javascript calling Flash function to upload file

I was wondering if i could get som suggestions on what the best approach to do the following would be...
I am currently calling a Flash AS3 function from Javascript (using jQuery) this function uploads a file which has already been selected in this flash file. Flash then uploads the file and calls a php file (upload.php) which handles the processed file. This all works fine. However there are other details that are filled out that pertain to the file uploaded (entered by the user in textboxes) All this data including the file path to where it has been uploaded must then be saved to a DB. Which can be done through an ajax call to another php file (processData.php). My issue is that when i upload the file i cant send the other details along with the file through flash (atleast not that i know of) which causes 2 different php scripts to execute. Secondly the other php script called through ajax doesnt have the file information to add to the DB. I can store this info in a session if i want but it just doesnt seem to convince me as the best way to go about this. Any other ideas or suggestions?
There is quite a bit of code I have so to avoid making this a HUGE question ill post the JS part that i think is important and some snippets of flash so you can have an idea of whats going on... If theres anyhting else youd like to see of the code feel free to ask and ill post it...
JS:
$("#uploadAudio").submit(function(event) {
event.preventDefault();
var form = $(this);
var title = form.find("#title").val();
var desc = form.find("#desc").val();
var flash = $("#flash");
var flashFileSet = flash.get(0).jsIsFileSelected();
if(flashFileSet)
{
$.ajax({
type: "POST",
url: "processData.php",
dataType: "text",
data: "title=" + title + "&desc=" + desc,
async: false,
success: function() {
audFile.get(0).jsUploadFile();
}
});
}
});
Flash
public function fUploader(){
req = new URLRequest();
req.url = ( stage.loaderInfo.parameters.f )? stage.loaderInfo.parameters.f : 'http://virtualmanagementonline.com/ajax/audUpload.php';
pFilterType = ( stage.loaderInfo.parameters.filterType )? stage.loaderInfo.parameters.filterType : 'Images';
pFileFilters = ( stage.loaderInfo.parameters.fileFilters )? stage.loaderInfo.parameters.fileFilters : '*.jpg;*.jpeg;*.gif;*.png';
file = new FileReference();
setup( file );
select_btn.addEventListener( MouseEvent.CLICK, browse );
progress_mc.bar.scaleX = 0;
tm = new Timer( 1000 );
tm.addEventListener( TimerEvent.TIMER, updateSpeed );
cancel_btn.addEventListener( MouseEvent.CLICK, cancelUpload );
cancel_btn.visible = false;
ExternalInterface.addCallback("jsUploadFile", uploadFile);
ExternalInterface.addCallback("jsIsFileSelected", IsFileSelected);
}
public function browse( e:MouseEvent ){
filefilters = [ new FileFilter(pFilterType, pFileFilters) ]; file.browse( filefilters );
}
private function selectHandler( e:Event ){
var tf = new TextFormat();
tf.color = 0x000000;
label_txt.defaultTextFormat = tf;
label_txt.text = file.name;
//file.upload( req );
}
public function IsFileSelected():Boolean{
if(label_txt.text != "")
{
return true;
}
else
{
return false;
}
}
public function uploadFile():void{
file.upload(req);
}
**Note: NOT all the flash code is shown since there is alot. I put up what i thought was needed to get an understanding of what exactly is going on.
If there is anything i can add for further details please let me know. Thanks in advance!
You can send as many data as you want to flash, since ExternalInterface is available.
ActionScript 3 Reference states the following about ExternalInterface:
From JavaScript on the HTML page, you can:
- Call an ActionScript function.
- Pass arguments using standard function call notation.
- Return a value to the JavaScript function.
All you have to do is register an ActionScript function/method as callable from the container:
ActionScript
...
ExternalInterface.addCallback("jsUploadFile", uploadFile);
...
public function uploadFile (title:String, desc:String):void
{
var infos:URLVariables = new URLVariables();
infos.desc = desc;
infos.title = title;
/* When you pass the URLVariables to data property of URLRequest,
all variables associated with the URLVariables object will be
sent to the server along with the image uploaded. */
req.data = infos;
file.upload(req);
}
Then, call it from the container (HTML) passing the additional information as parameters.
JavaScript
$("#uploadAudio").submit(function(event) {
event.preventDefault();
var form = $(this);
var title = form.find("#title").val();
var desc = form.find("#desc").val();
var flash = $("#flash");
var flashFileSet = flash.get(0).jsIsFileSelected();
if(flashFileSet)
{
/* Instead of sending title and desc to the server via ajax, pass
them as parameters to the jsUploadFile method. So
you can handle everything in one place */
audFile.get(0).jsUploadFile(title, desc);
}
});
Hope it helps.

Flash calling a PHP function

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&paramName2=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/ ?

Categories