I'm completely new to Flash and AS3. I've Googled around an cannot find anything on this topic.
I have some code that posts an image to a php file:
var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
var jpgURLRequest:URLRequest = new URLRequest("http://127.0.0.1/gdipORG/takeImage.php");
jpgURLRequest.requestHeaders.push(header);
jpgURLRequest.method = URLRequestMethod.POST;
jpgURLRequest.data = byteArray;
navigateToURL(jpgURLRequest, "blank");
Problem is, for the actual posting to take place, I have to navigate to the actual url (see last line of code)...
I want to be able to post the data to the url without having to navigate to it. Any ideas?
Use a URLLoader right after your existing code:
//Existing code
var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
var jpgURLRequest:URLRequest = new URLRequest("http://127.0.0.1/gdipORG/takeImage.php");
jpgURLRequest.requestHeaders.push(header);
jpgURLRequest.method = URLRequestMethod.POST;
jpgURLRequest.data = byteArray;
//KILL THIS LINE navigateToURL(jpgURLRequest, "blank");
//Add these (UNTESTED CODE):
var sendJPGLoader:URLLoader = new URLLoader();
sendJPGLoader.dataFormat = URLLoaderDataFormat.BINARY;
sendJPGLoader.addEventListener(Event.COMPLETE, sendJPGToServerComplete);
sendJPGLoader.addEventListener(IOErrorEvent.IO_ERROR, sendJPGToServerIOError);
//Try to send image
sendJPGLoader.load(jpgURLRequest);
function sendJPGToServerComplete(evt:Event):void {
//Request was sent to server succesfully
//Optionally check server response
// var serverResponse:String = String(evt.target.data);
}
function sendJPGToServerIOError(evt:Event):void {
//Failed
}
At the top of your code don't forget to import:
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
I think I got them all :)
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 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.*;
I am having trouble with OAuthorization, I have a flash player application requesting a PHP script.
The PHP is always returning:
{"status":false,"message":"Invalid Signature"}
I tried two differents libraries:
https://github.com/yahoo/yos-social-as3
https://github.com/iotashan/oauth-as3
I dont know what do try anymore, could someone help me with this?
The as3 script that is generating a wrong URL:
import com.yahoo.oauth.OAuthRequest;
import com.yahoo.oauth.OAuthConsumer;
import com.yahoo.oauth.OAuthSignatureMethod_HMAC_SHA1;
import com.yahoo.oauth.IOAuthSignatureMethod;
import com.yahoo.oauth.OAuthToken;
import com.yahoo.oauth.OAuthUtil;
var signature:IOAuthSignatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
var consumer:OAuthConsumer = new OAuthConsumer("myKey", "mySecret");
var oauthRequest:OAuthRequest =
new OAuthRequest(
"GET",
"http://mySite.com/index.php",
null,
consumer,
null
);
var request:URLRequest = new URLRequest(oauthRequest.buildRequest(signature));
var loader:URLLoader = new URLLoader;
loader.addEventListener(Event.COMPLETE, getComplete);
loader.load(request);
function getComplete(event:Event):void
{
trace("data", URLLoader(event.currentTarget).data);
}
I have a example did in PHP script that generate a correct URL:
<?php
// include oath
require_once('OAuth/OAuth.php');
if ($mode == 'generate')
{
$consumer = new OAuthConsumer(OAUTHKEY, OAUTHSECRET);
$sig_method = new OAuthSignatureMethod_HMAC_SHA1;
// call this file
$api_endpoint = $_GET['url'];
//use oauth lib to sign request
$req = OAuthRequest::from_consumer_and_token($consumer, null, 'GET', $api_endpoint, $parameters);
$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
$req->sign_request($sig_method, $consumer, null); //note: double entry of token
echo $req->to_url();
exit;
}
This is the url generated by the PHP script, this work:
http://mySite.com/index.php?
oauth_consumer_key=myKey&
oauth_nonce=20de438daf761115018b3d6f26456a6e&
oauth_signature=JpWrfU77Pl%2FfFoa%2BhVy8agq9I5Q%3D&
oauth_signature_method=HMAC-SHA1&
oauth_timestamp=1347583047&
oauth_version=1.0
This is the url generated by the AS3 script, this not work:
http://mySite.com/index.php?
oauth_consumer_key=myKey&
oauth_nonce=b8808c76e9aaa264964aefabb22bdc55&
oauth_signature=jZ31R4C0Ybj1dluIjy6wKCtN7D4%3D&
oauth_signature_method=HMAC-SHA1&
oauth_timestamp=1348705359&
oauth_version=1.0
Solved :)
Thanks to PeeHaa that told I was using a version 2.0 library, now I am using back the iotashan lib, that is version 1.0 and it is working now :)
import org.iotashan.oauth.IOAuthSignatureMethod;
import org.iotashan.oauth.OAuthConsumer;
import org.iotashan.oauth.OAuthRequest;
import org.iotashan.oauth.OAuthSignatureMethod_HMAC_SHA1;
import org.iotashan.oauth.OAuthToken;
import org.iotashan.utils.OAuthUtil;
import org.iotashan.utils.URLEncoding;
var signature:IOAuthSignatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
var consumer:OAuthConsumer = new OAuthConsumer("myKey", "mySecret");
var oauthRequest:OAuthRequest =
new OAuthRequest(
OAuthRequest.HTTP_METHOD_GET,
"http://mySite.com/index.php",
null,
consumer,
null
);
var request:URLRequest = new URLRequest(oauthRequest.buildRequest(signature, OAuthRequest.RESULT_TYPE_URL_STRING));
// Creating URLLoader to invoke Google service
var loader:URLLoader = new URLLoader;
loader.addEventListener(Event.COMPLETE, getComplete);
loader.load(request);
trace("request", request.url);
function getComplete(event:Event):void
{
trace("data", URLLoader(event.currentTarget).data);
}
I know this is frequently asked, but I have looked all over the internet to find the mistake I'm making with the code I've used to send and receive data from AS3 to PHP and viceversa. Can you find the mistake? Here is my code:
AS3:
import flash.events.MouseEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequestMethod;
import flash.events.Event;
submitbtn.addEventListener(MouseEvent.CLICK, sendData)
function sendData(event:MouseEvent):void
{
var loader : URLLoader = new URLLoader;
var urlreq:URLRequest = new URLRequest("http://[mydomain]/test.php");
var urlvars: URLVariables = new URLVariables;
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
urlreq.method = URLRequestMethod.POST;
urlvars.uname = nametxt.text;
urlvars.apellido = aptxt.text;
urlvars.email = emtxt.text;
urlvars.cedula = cctxt.text;
urlvars.score = scoretxt.text;
urlreq.data = urlvars;
loader.addEventListener(Event.COMPLETE, completed);
loader.load(urlreq);
}
function completed(event:Event): void
{
var loader2: URLLoader = URLLoader(event.target);
trace(loader2.data.done);
resptxt.text = event.target.data.done;
}
PHP inside of [domain]/test.php:
<?php
$username = $_POST["uname"];
$apellido = $_POST["apellido"];
$cedula = $_POST["cedula"];
$email = $_POST["email"];
$score = $_POST["score"];
print_r($_POST);
if (!($link=mysql_connect(databasemanager,username,password)))
{
echo "Error conectando a la base de datos.";
exit();
}
if (!mysql_select_db(database,$link))
{
echo "Error seleccionando la base de datos.";
exit();
}
try
{
mysql_query("insert into scores(name,lastName,email,document,score) values('$username','$apellido','$email','$cedula','$score')",$link);
print "done=true";
}
catch(Exception $e)
{
print "done=$e->getMessage()";
}
echo "done=true";
?>
Thanks for your answers.
Your AS code seems to be right. So the problem might be in PHP. Please test first with this PHP file:
<?php
echo "test=1&done=true";
?>
This should then let your movie trace "true".
You then should debug your PHP. print_r($_POST); destroys your output of course. May be you did forget to remove this debugging statement :-)
#Jesse and #Ascension Systems, check the docs for URLVariables: http://livedocs.adobe.com/flash/9.0_de/ActionScriptLangRefV3/flash/net/URLVariables.html
Try
submitbtn.addEventListener(MouseEvent.CLICK, sendData);
function sendData(event:MouseEvent):void
{
var urlreq:URLRequest = new URLRequest ("http://[mydomain]/test.php");
urlreq.method = URLRequestMethod.POST;
var urlvars:URLVariables = new URLVariables();
urlvars.uname = nametxt.text;
urlvars.apellido = aptxt.text;
urlvars.email = emtxt.text;
urlvars.cedula = cctxt.text;
urlvars.score = scoretxt.text;
urlreq.data = urlvars;
var loader:URLLoader = new URLLoader (urlreq);
loader.addEventListener(Event.COMPLETE, completed);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(urlreq);
}
public function completed (event:Event):void{
var variables:URLVariables = new URLVariables( event.target.data );
resptxt.text = variables.done;
}
Updated the completed function... and corrected missing bracket.
First of all, change this line of code:
trace(loader2.data.done);
to this:
trace(loader2.data);
You're outputting raw text from php, so your data object in flash is just gonna be raw text. It's not an object with .done attached to it. If you want to have a data structure then you need to create some XML or something inside PHP, print that out and then cast loader2.data as XML, like so:
var returnedData:XML = new XML(loader2.data);
However, if your XML is not formed correctly, you'll create an uncaught error in flash and crash your app, so make sure you use try/catch statements.
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! ;)