ActionScript - Contact Form Not Working - php

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... :)

Related

Can't upload images to the server on mobile

I am looking for any pointers what I am doing wrong here?
Situation:
I created a simple form on my website that requires the user to enter some text data and an image. This information is then stored on the server - picture separately, and the text data in a json file.
I have tested it with multiple image formats on my desktop (I allow only the most common types, such as jpg, png, or bmp). All seems to be fine. However, it isn't so smooth on mobile (iOS). When I attempt to upload a screenshot (shows as a png format), or a picture I just took (jpg), the response that comes back says Missing picture, which means that no data was received on the server. The thing is that this is not always the case, some screenshots come through, some don't.
I am encoding the picture as a base64 string on the client. I tried logging it to make sure it goes through, and it seems to be fine. However, when I log the received parameters on the server, in these failed cases, the picture string is really empty! All I do is I read the $_REQUEST or $_POST parameters (it's in PHP).
This error has been replicated only on mobile so far. On the front side, I guess this is the most relevant piece of code, but if you need more let me know! You can also inspect that website I included, but it will be slightly more difficult as it's minified.
function init_form_submit () {
var button = document.getElementById('form-submit-btn'),
image_upload_button = document.getElementById('picture');
if (!button || !image_upload_button) return;
image_upload_button.addEventListener('change', function (event) {
preview_image(this);
});
button.addEventListener('click', function (event) {
// Hijack the form submit.
event.preventDefault();
show_form_loader();
var form_validator = FormValidator(GLOB.form_node);
if (!form_validator.valid) {
form_submitted_callback();
}
else {
var http = new XMLHttpRequest();
var formData = new FormData();
formData.append("about", form_validator.fd.about);
formData.append("email", form_validator.fd.email || '');
formData.append("handle", form_validator.fd.handle);
formData.append("name", form_validator.fd.name);
formData.append("picture", GLOB.picture);
http.open('POST', 'https://lmen.us/royalkitten/api/apply-royal-kitten/index.php', true);
http.setRequestHeader('Content-type', 'multipart/form-data');
http.onreadystatechange = function () {
var response;
if (http.readyState !== 4 || http.status !== 200) return;
try {
response = JSON.parse(http.responseText);
}
catch (error) {
response = http.responseText;
console.log(response);
}
form_submitted_callback(response);
}
http.send(formData);
}
});
}
Here is how I store the image data in the GLOB.picture variable. This function is called only twice - once in the code above when the user chooses an image, and once in a callback after a successful submission as a way to reset the form to its original state.
function preview_image (input) {
var preview_label = document.getElementById('picture-label'),
preview_element = document.getElementById('picture-preview');
if (!input.files.length) {
if (preview_label) {
preview_label.innerHTML = 'Select a file';
}
if (preview_element) {
preview_element.src = './images/image-placeholder-600x600.jpg';
}
GLOB.picture = null;
return;
}
var reader = new FileReader(),
file = input.files[0];
if (!file) return;
reader.onload = function (event) {
var image_data = event.target.result;
if (preview_label) {
preview_label.innerHTML = file.name;
}
if (preview_element) {
preview_element.src = image_data;
}
GLOB.picture = image_data;
}
reader.readAsDataURL(file);
}
I guess, the problem is that your image is probably bigger than PHP max size allowed for a POST request. You should send your form as multipart/form-data, and send your image as a file. On the server side, you should get it via $_FILE instead of $_POST...
To send your image as a file, there are multiple solutions. First, you could send a base-64 encoded Blob, but it would be 30% larger than the original file (because of base-64 encoding).
What I would recommend to you is that you send the file in its original binary format, which is easier to implement and faster to upload.
To do so, you just need to send as-is the content of input.files[0]. let's say you set a GLOB.pictureFile=input.files[0] in your preview_image() function. you then just send it in the form like this :
formData.append("picture", GLOB.pictureFile);

Ajax response while remote php runs

i want to get data echoed in the remote php after i sent the main request and before i get the complete response.
the intent is to show "i am almost there - 5 items remaining" or similer...
This is my current js script:
function getdetails(){
$("div#urltable").fadeOut('fast');
$("div#ajaxLoading").fadeIn('fast');
var checkurl = $('input#remoteurl').attr('value');
if($("#checkBrokenLinks").prop('checked') == true){
var checkonline = 'check';
}
else {
var checkonline = 'skip';
}
$.ajax({
type: "POST",
url: "ajax-outlink_checker.php",
data: {checkurl:checkurl, checkonline: checkonline}
}).always(function(data) {
var $response = $(data);
var whileRuningCount = $response.filter('#whileRuningCount').html();
$("div#whileRuningCount").fadeOut('fast');
$("div#whileRuningCount").fadeIn('fast');
$("div#whileRuningCount").html(whileRuningCount);
}).done(function(result) {
var $response=$(result);
var urltable = $response.filter('#urltable').html();
var whileRuningCount = $response.filter('#whileRuningCount').html();
$("div#ajaxLoading").fadeOut('fast');
$("div#urltable").fadeIn('fast');
$("div#urltable").html(urltable);
});
}
As you can see
i added .always() trying to grab the echo's the run in the php file.
but... i guess i missunderstand how to make it work and if .always
is even the way to go about it.
Any help would be most apreaciated.
Best regards, Sagive.
You'll need to make 2 separate ajax calls. 1 for the initial request, and then a second one repeated as often as needed to check for status updates. The action responder will need to update some variable for the status responder to check. How you communicate the status to the other responder is up to you. One method is to simply use a file. Your action responder will call handleaction() while the status responder will only call statuscheck():
<?php
function handleaction()
{
$actions_left = 0;
while ($actions_left > 0)
{
perform_action();
status_update(--$actions_left);
}
}
function status_update($remaining)
{
$filename = "/" . session_id() . "_action_status.txt";
$fh = fopen($filename, "w");
fputs($fh, $remaining);
fclose($fh);
}
function statuscheck()
{
$filename = "/" . session_id() . "_action_status.txt";
echo #file_get_contents($filename); // js treats empty response as 0.
}
?>
.always() is not for that. It just means that whether the request was success/done() or fail() run what is in that snippet.
If you are trying to show an "almost there.." message, a better way would be to have another async call to the server which polls every N seconds, looks at some data state in the server, (a flag maybe?) and based on that shows a message in the front end..

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.

Using JS setTimeout to post AJAX requests in a loop, but setTimeout gets called far too often

This question has been answered. The problem was that myEventMoveTrainManaul() was being called from other locations within the code. Thanks to everyone who offered their help.
Please forgive me for re-posting this, but it was getting almost no attention and it's very important that I find someone to help me with this. Thank you for your kind understanding.
I have been working on a new feature for a facebook game I have written. The game allows a player to travel between cities in Europe by train and deliver goods for profit. This feature that I'm adding adds pathfinding AI to the game: it allows a player to select a city to travel to, then the game automatically moves the player's train along track from it's starting city to the destination city. I am using AJAX and setTimeout() to get the data from the backend and to enable the movement of the train along the track that connects cities. Please refer to the code which will (hopefully) contain a better understanding of what I am attempting to do.
The problem is that setTimeout() gets called too often. I put a global variable called statusFinalDest which may contain two values: ENROUTE and ARRIVED. While the train is ENROUTE, the JS train movement function calls itself using setTimeout until the backend returns a statusFinalDest of ARRIVED, at which time the train movement timeout loop is (supposedly) terminated. However, instead of calling myEventMoveTrainManual() once for each turn the backend processes, it gets called exceedingly more often, as if it is not recognizing the changed state of statusFinalDest. I have attempted to put more limiting structures into the code to put an end to this excessive behavior, the they don't appear to be working.
FYI - myEventMoveTrainManual() is not an event handler, but it does get called from an event handler.
Here's the relevant FBJS (Facebook JS) code:
function myEventMoveTrainManual(evt) {
if(mutexMoveTrainManual == 'CONTINUE') {
//mutexMoveTrainManual = 'LOCKED';
var ajax = new Ajax();
var param = {};
if(evt) {
var cityId = evt.target.getParentNode().getId();
var param = { "city_id": cityId };
}
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
statusFinalDest = data.status_final_dest;
if(data.code != 'ERROR_FINAL_DEST') {
// Draw train at new location
trackAjax = new Ajax();
trackAjax.responseType = Ajax.JSON;
trackAjax.ondone = function(trackData) {
var trains = [];
trains[0] = trackData.train;
removeTrain(trains);
drawTrack(trackData.y1, trackData.x1, trackData.y2, trackData.x2, '#FF0', trains);
if(data.code == 'UNLOAD_CARGO') {
unloadCargo();
} else if (data.code == 'MOVE_TRAIN_AUTO' || data.code == 'TURN_END') {
moveTrainAuto();
} else {
/* handle error */
}
mutexMoveTrainManual = 'CONTINUE';
}
trackAjax.post(baseURL + '/turn/get-track-data');
}
}
ajax.post(baseURL + '/turn/move-train-set-destination', param);
}
// If we still haven't ARRIVED at our final destination, we are ENROUTE so continue
// moving the train until final destination is reached
// statusFinalDest is a global var
if(statusFinalDest == 'ENROUTE') {
setTimeout(myEventMoveTrainManual, 1000);
}
}
And here is the backend PHP code:
public function moveTrainSetDestinationAction() {
require_once 'Train.php';
$trainModel = new Train();
$userNamespace = new Zend_Session_Namespace('User');
$gameNamespace = new Zend_Session_Namespace('Game');
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$trainRow = $trainModel->getTrain($userNamespace->gamePlayerId);
$statusFinalDest = $trainRow['status_final_dest'];
if($statusFinalDest == 'ARRIVED') {
$originCityId = $trainRow['dest_city_id'];
$destCityId = $this->getRequest()->getPost('city_id');
if(empty($destCityId)) {
// If we arrived at final dest but user supplied no city then this method got called
// incorrectly so return an error
echo Zend_Json::encode(array('code' => 'ERROR_FINAL_DEST', 'status_final_dest' => $statusFinalDest));
exit;
}
$gameNamespace->itinerary = $this->_helper->getTrainItinerary($originCityId, $destCityId);
array_shift($gameNamespace->itinerary); //shift-off the current train city location
$trainModel->setStatusFinalDest('ENROUTE', $userNamespace->gamePlayerId);
$statusFinalDest = 'ENROUTE';
}
$cityId = $trainRow['dest_city_id'];
if($trainRow['status'] == 'ARRIVED') {
if(count($gameNamespace->itinerary) > 0) {
$cityId = array_shift($gameNamespace->itinerary);
}
}
$trainRow = $this->_helper->moveTrain($cityId);
if(count($trainRow) > 0) {
if($trainRow['status'] == 'ARRIVED') {
// If there are no further cities on the itinerary, we have arrived at our final destination
if(count($gameNamespace->itinerary) == 0) {
$trainModel->setStatusFinalDest('ARRIVED', $userNamespace->gamePlayerId);
$statusFinalDest = 'ARRIVED';
}
echo Zend_Json::encode(array('code' => 'UNLOAD_CARGO', 'status_final_dest' => $statusFinalDest));
exit;
// Pass id for last city user selected so we can return user to previous map scroll postion
} else if($trainRow['track_units_remaining'] > 0) {
echo Zend_Json::encode(array('code' => 'MOVE_TRAIN_AUTO', 'status_final_dest' => $statusFinalDest));
exit;
} else { /* Turn has ended */
echo Zend_Json::encode(array('code' => 'TURN_END', 'status_final_dest' => $statusFinalDest));
exit;
}
}
echo Zend_Json::encode(array('code' => 'MOVE_TRAIN_AUTO_ERROR'));
}
Based on #brad's suggestion, I have modified myEventMoveTrainManual() as follows:
function myEventMoveTrainManual(evt) {
//debugger;
if(mutexMoveTrainManual == 'CONTINUE') {
//mutexMoveTrainManual = 'LOCKED';
//statusFinalDest = 'ARRIVED';
var ajax = new Ajax();
var param = {};
if(evt) {
var cityId = evt.target.getParentNode().getId();
var param = { "city_id": cityId };
}
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
statusFinalDest = data.status_final_dest;
//debugger;
consoleLog('statusFinalDest='+statusFinalDest+', data.code='+data.code);
if(data.code != 'ERROR_FINAL_DEST') {
consoleLog('data.code != ERROR_FINAL_DEST');
// Draw train at new location
trackAjax = new Ajax();
trackAjax.responseType = Ajax.JSON;
trackAjax.ondone = function(trackData) {
consoleLog('drawing track');
var trains = [];
trains[0] = trackData.train;
removeTrain(trains);
drawTrack(trackData.y1, trackData.x1, trackData.y2, trackData.x2, '#FF0', trains);
consoleLog('processing data.code = '+data.code);
if(data.code == 'UNLOAD_CARGO') {
unloadCargo();
consoleLog('returned from unloadCargo()');
} else if (data.code == 'MOVE_TRAIN_AUTO' || data.code == 'TURN_END') {
moveTrainAuto();
consoleLog('returned from moveTrainAuto()');
/*
} else if (data.code == 'TURN_END') {
consoleLog('moveTrainManual::turnEnd');
turnEnd();
*/
} else {
/* handle error */
}
mutexMoveTrainManual = 'CONTINUE';
// If we still haven't ARRIVED at our final destination, we are ENROUTE so continue
// moving the train until final destination is reached
if(statusFinalDest == 'ENROUTE') {
myEventMoveTrainManual(null);
}
}
trackAjax.post(baseURL + '/turn/get-track-data');
}
}
ajax.post(baseURL + '/turn/move-train-set-destination', param);
}
// If we still haven't ARRIVED at our final destination, we are ENROUTE so continue
// moving the train until final destination is reached
//if(statusFinalDest == 'ENROUTE') {
// clearTimeout(timerId);
// timerId = setTimeout(myEventMoveTrainManual, 1000);
//}
}
However, the original problem still manifests: myEventMoveTrainManual() gets called too many times.
you need your setTimeout to be within the callback of your ajax call (ajax.onDone if I'm reading this correctly)
I'm assuming you want your ajax call to be called again only after the first call has completed. Currently, this code will execute your function once a second, unconcerned with the pending asynchronous calls.
Is that what you want? Or do you want it to be executed one second after your ajax returns? If the latter, put your setTimeout within that callback and you'll only get the next request 1s after your ajax returns.
edit with adjusted example:
I still don't see your setTimeout within the ajax call. Here's some pseudo code and an explanation:
function myFunc(){
var ajax = new Ajax();
ajax.onDone = function(data){
// do some stuff here (ie modify mutex)
// now trigger your setTimeout within this onDone to call myFunc() again:
setTimeout(myFunc,1000);
}
ajax.post("someURL")
}
explanation
Here's what happens, you call myFunc(), it instantiates your ajax object and makes the call. When that ajax returns, you do whatever you want to do, then call myFunc() again (the setTimeout) after x amount of milliseconds (inside onDone). This instantiates your ajax object and makes the call...
I am not sure of the code but, but problem seems like this:
You are checking if statusFinalDest == 'ENROUTE' at the client side, which does not work.
Place a timer based counter on the server side before setting the global value to ENROUT and not setting it every time ie set 1 sec delay in setting the value also, as any client side method would get overridden by a fresh copy of js code.
Your Ajax-calls are asynchronous. I think even if the back end is ready, the response needs some time to get back to the client. Meanwhile the client sends more Ajax-requests.
(edit: Your changes approve that this is not the problem)
it seems that you registered an event listener for a DOM-event like mouse-click, because you are checking the evt-argument.Please post the code of your event handler and the part of the code, where you register the event.
Who says that there are too much calls? I can't see count-variables in the server/client scripts; Note that log-items are sometimes added very late to the console, they are not a indicator to my eyes.I think it's very important to know your indicators!

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