What am I doing wrong trying to get data with URLLoader? - php

Hey, I have a php document dynamicly generating the following:
peerID=e224d6cac76ef3181d4804858d82ebeee7e67ad7bdd7b02f3857a700b0ec7fbc
(from get_peerID.php)
I'm using the following AS3 to try and get this data:
private var myLoader:URLLoader = new URLLoader();
private function sendData():void {
writeText("sending data...");
var objSend:Object = new Object;
objSend.peerID = myID.text;
put_peerID.send( objSend );
writeText("http://localhost/example.com/scripts/get_peerID.php?peerID=" + myID.text);
var myRequest:URLRequest = new URLRequest("http://localhost/example.com/scripts/get_peerID.php?peerID=" + myID.text);
myRequest.contentType = "text/plain";
//var myLoader:URLLoader = new URLLoader();
myLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
configureListeners(myLoader); //.addEventListener(Event.COMPLETE,onComplete);
myLoader.load(myRequest);
}
private function configureListeners(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.COMPLETE, completeHandler);
dispatcher.addEventListener(Event.OPEN, openHandler);
dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
}
private function completeHandler(event:Event):void {
writeText("completeHandler: " + myLoader.data.peerID);
}
private function openHandler(event:Event):void {
writeText("openHandler: " + event);
}
private function progressHandler(event:ProgressEvent):void {
writeText("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
writeText("securityErrorHandler: " + event);
}
private function httpStatusHandler(event:HTTPStatusEvent):void {
writeText("httpStatusHandler: " + event);
}
private function ioErrorHandler(event:IOErrorEvent):void {
writeText("ioErrorHandler: " + event);
}
Which generates the following text (from writeText()):
sending data...
http://localhost/example.com/scripts/get_peerID.php?peerID=5131079b60ba3ae05f9d54568896db1e04f772f97bb98c6d525cb8ba3032798b
openHandler: [Event type="open" bubbles=false cancelable=false eventPhase=2]
httpStatusHandler: [HTTPStatusEvent type="httpStatus" bubbles=false cancelable=false eventPhase=2 status=200 responseURL=null]
So, its not giving me the data that I need. I'm not sure what to try next. I've been in and out of forums all day so any help would be appreciated.

It's not working because I was running it on my localhost. Adobe says:
For Flash Player 8 and later:
Data loading is not allowed if the
calling file is in the
local-with-file-system sandbox and
the target resource is from a network
sandbox.
Data loading is also not allowed if
the calling file is from a network
sandbox and the target resource is
local.
After released it and put it up online it work.

Related

Actionscripts3 read JSON from VPS issue

In Adobe AIR Dektop, I wrote some code to read JSON data from our VPS, I think my AS3 codes are true but I'm not sure about the PHP codes. Adobe Animate console is empty after I run project.
This program have access to other sites and after run i can read data from them, but from our VPS i can't.
AS3:
import flash.events.*;
import flash.net.*;
var loader: URLLoader;
var request: URLRequest;
function load(): void {
request = new URLRequest("212.73.150.148/asphp.php");
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onComplete);
loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
loader.load(request);
}
function onError(e: Event): void {
trace(e.target.data + "READING DATA FROM VPS ERROR");
}
function onComplete(e: Event) {
trace(e.target.data);
var json: Object = JSON.parse(e.target.data);
trace("json.DATA1 = ", json.DATA1);
trace("json.DATA2 = ", json.DATA2);
}
load();
PHP:
<?php
$arr = array ('DATA1'=>"111",'DATA2'=>"222");
header('Content-Type: application/json');
echo json_encode($arr);
?>
I used wrong URL value "212.73.150.148/asphp.php" after change to "http://212.73.150.148/asphp.php" it worked.

Error #2101 Don't understand why [duplicate]

I have this flash code. It sends score and username in my game to savescores.php. But I have the error above. I have changed URLLoaderDataForma.VARIABLES to TEXT but still same error occurs. What should i do to fix this problem? Thanks in advance..
private function SendScore(score:int)
{
var variables:URLVariables = new URLVariables();
variables.score = score;
variables.username = username;
var urlloader:URLLoader = new URLLoader();
var urlrequest:URLRequest = new URLRequest('http://localhost:90/savescores.php');
urlrequest.method = URLRequestMethod.POST;
urlrequest.data = variables;
urlloader.dataFormat = URLLoaderDataFormat.TEXT;
urlloader.load(urlrequest);
urlloader.addEventListener(Event.COMPLETE, CompleteHandler, false, 0, true);
urlloader.addEventListener(IOErrorEvent.IO_ERROR , ErrorHandler, false, 0, true);
}
private function CompleteHandler(e:Event)
{
var vars:URLVariables = new URLVariables(e.target.data);
if(vars.success) trace('Saving succeeded');
else ('Saving failed');
}
private function ErrorHandler(e:IOErrorEvent)
{
trace('Error occured');
}
ANSWER: Issue was with PHP
-- You must return a var to AS3 or you will get this error.
I am posting this because unless the viewer reads the comments they will not know what the issue was and a solution. Anil, who asked this question stated it was an issue with the PHP and not as3 but gave no reason as to why. It seems the answer marked correct above is not a sufficient answer because it only suggests a possible solution. Where Anil, admitted it was an issue with the php. I believe this answer is more complete and can help someone who has this same issue.
I had a similar issue. The problem was with the php. Unless you output something back from the php you will get this error.
Flash did not like nothing being returned from php and gave the following 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()
Here was a part of my PHP that did not return anything:
if($ConfirmedEmail=="true")
{
echo "Status=true";
}
if($ConfirmedEmail=="false")
{
echo "Status=false";
}
But if it was neither true/false it would OUTPUT NOTHING. = Flash Does Not Like!
So the PHP code had to be this:
if($ConfirmedEmail=="true")
{
echo "Status=true";
}
else if($ConfirmedEmail=="false")
{
echo "Status=false";
}
else
{
echo "Status=Nada";
}
Here is my AS3 code for you to look at. Hope it helps someone.
public function checkEmail(e:Event = null)
{
var urlreq = new URLRequest("http://www.MyWebsite.com/myScript.php");
urlreq.method = URLRequestMethod.POST;
var urlvars = new URLVariables();
urlvars.userID = Main.userID;
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);
trace("Email Confirmed: " + variables.Status);
}
I assume that the problem is not with request, but with response handling. You are instantiating vars as URLVariables, but probably e.target.data does not comply with the format expected. Trace e.target.data value to get more information.

Actionscript3 SecurityError #2048

I have a problem with loading data from my PHP server. I can access it simply by link but in actionscript when I'm trying to load it just like in this thread: Get and parse JSON in Actionscript it is not working.
It just throws an event
[SecurityErrorEvent type="securityError" bubbles=false
cancelable=false eventPhase=2 text="Error #2048"].
What should I do? I've read something about cross-domain-policy so I have added file crossdomain.xml to PHP server like this:
<cross-domain-policy>
<site-control permitted-cross-domain-policies="all"/>
<allow-access-from domain="*"/>
<allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>
I tried adding this file almost everywhere. Can I do something more?
Code responsible for loading this data:
private function getURL():void
{
var request:URLRequest=new URLRequest("http://Journey.pe.hu/Journey/Users/");
ExternalInterface.call("console.log", request.url);
request.requestHeaders=[new URLRequestHeader("Content-Type", "application/json")];
request.method=URLRequestMethod.GET;
var loader:URLLoader=new URLLoader();
loader.addEventListener(Event.COMPLETE, receive);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, notAllowed);
loader.addEventListener(IOErrorEvent.IO_ERROR, notFound);
loader.load(request);
ExternalInterface.call("console.log", "l1");
}
protected function notAllowed(event:SecurityErrorEvent):void
{
ExternalInterface.call("console.log", event.toString());
}
protected function notFound(event:IOErrorEvent):void
{
ExternalInterface.call("console.log", "NOT FOUND");
}
protected function receive(event:Event):void
{
ExternalInterface.call("console.log", "Nameldasodoad");
var loader:URLLoader = URLLoader(event.target);
var jsonArray:Array = com.adobe.serialization.json.JSON.decode(loader.data);
//ExternalInterface.call("console.log", "Name " + jsonArray[0].Name);
//var jsonArray:Array = com.adobe.serialization.JSON.decode(loader.data);
}
Where did you add crossdomain.xml?
Basically, it should add at root directory.
In this case
http://journey.pe.hu/crossdomain.xml
By default, flash loads crossdomain.xml from root automatically.
If you can't add there, add here
http://Journey.pe.hu/Journey/crossdomain.xml
and load manually.
private function getURL():void
{
// load crossdomain.xml manually.
Security.loadPolicyFile("http://Journey.pe.hu/Journey/crossdomain.xml");
var request:URLRequest=new URLRequest("http://Journey.pe.hu/Journey/Users/");
ExternalInterface.call("console.log", request.url);
request.requestHeaders=[new URLRequestHeader("Content-Type", "application/json")];
request.method=URLRequestMethod.GET;
var loader:URLLoader=new URLLoader();
loader.addEventListener(Event.COMPLETE, receive);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, notAllowed);
loader.addEventListener(IOErrorEvent.IO_ERROR, notFound);
loader.load(request);
ExternalInterface.call("console.log", "l1");
}

Load JSON data with URL loader

I am new to action script 3.0. Help me to understand how can I load data with URLLoader.
So, I have an aplication like:
var PATH:String = "http://www.somesite.com/myFirstPage.php?a=10&b=20";
var urlRequest:URLRequest = new URLRequest(PATH);
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete);
urlLoader.load(urlRequest);
function urlLoader_complete(evt:Event):void {
some_result = urlLoader.data;
}
php script looks like:
<?php
//retrieve GET params
int c = a + b; //a and b come from GET request
return "{{"result_equal":"20"}}"; //result in JSON
?>
I don't really understand how JSON result from .php page gets in my URLLoader object. Help me by simple example, please. Thanx!
You need a few things here. First off, you'll need a JSON library, because somehow it isn't built into Flash, even with their modified E4X core:
https://github.com/mikechambers/as3corelib
This should give you the following bits of code:
import com.adobe.serialization.json.JSON;
function urlLoader_complete(e:Event):void
{
var loader:URLLoader = URLLoader(e.target);
var some_result:Object = JSON.decode(loader.data);
}
Now... your PHP code is a mess. The best way to create JSON is to just use the json_encode function:
$retVal = array('result_equal'=>20);
echo json_encode($retVal);
You will want to use this project: https://github.com/mikechambers/as3corelib
Example usage:
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.rpc.events.ResultEvent;
import com.adobe.serialization.json.JSON;
private function onJSONLoad(event:ResultEvent):void
{
var rawData:String = String(event.result);
var arr:Array = (JSON.decode(rawData) as Array);
var dp:ArrayCollection = new ArrayCollection(arr);
grid.dataProvider = dp;
}
]]>
</mx:Script>
<mx:HTTPService
id="service"
resultFormat="text"
url="http://weblogs.macromedia.com/mesh/mashedpotato.json"
result="onJSONLoad(event)" />
PHP code should looks like this:
$result = array("result_equal" => 20);
return json_encode($result);
So, this is what I get: Please, say whats wrong, what good! Thanx1
package
{
import data.*;
import flash.errors.IOError;
import flash.events.Event;
import flash.events.*;
import flash.net.*;
public class UserInfoProxy
{
public static const GET_USER_INFO:DataCallConfigVO = new DataCallConfigVO( "COMMON", 'GET_USER_INFO', true, null, null);
public function UserInfoProxy()
{
trace("Start request");
var request:URLRequest = new URLRequest("http://www.avrora.com.localhost/myservlet.php");
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, completeHandler);
loader.addEventListener(ProgressEvent.PROGRESS, progressHandler);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
loader.load(request);
}
private function completeHandler(event:Event):void
{
var loader:URLLoader = URLLoader(event.target);
trace("Complete");
trace("completeHandler: " + loader.data);
}
private function progressHandler(event:ProgressEvent):void
{
trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
}
private function securityErrorHandler(event:SecurityErrorEvent):void
{
trace("securityErrorHandler: " + event);
}
private function httpStatusHandler(event:HTTPStatusEvent):void
{
trace("httpStatusHandler: " + event);
}
private function ioErrorHandler(event:IOErrorEvent):void
{
trace("ioErrorHandler: " + event);
}
}
}
And this is my PHP code, that must return JSON data:
<?
//here I can process all input GET, POST params, database etc...
$someJSONresponse = "{'username':'yozhik', 'age':'18'}";
//here just echo result and it will be automatically downloaded??
echo $someJSONresponse;
?>

How do I integrate Flash with Php

I want to integrate my flash file with php code. I got the below code from
http://www.kirupa.com/developer/actionscript/flashphpxml_integration2.htm
function lv(l, n, t, e, f) {
if (l == undefined) {
l = new LoadVars();
l.onLoad = function () {
var i;
n.htmlText = "";
if (t == undefined) {
n.htmlText += "<b>" + this["title" + e] + "</b><br>";
} else {
for (i = 0; i < this.n; i++) {
n.htmlText += "<a href='" + this["link" + i] + "'>" + this["title" + i] + "</a><br>";
}
}
};
}
l.load(f);
}
lv(sites_txt, "cycle", null, "sites.php");
I did all the steps given in that forum but while running that code i got error Like
1180: Call to a possibly undefined method LoadVars.
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..
1136: Incorrect number of arguments. Expected 5.
I am new to the flash scripting please guide me how to troublshooting these
Your example code was in AS2, here's how you send and receive data from and to PHP using AS3 using:
URLRequest
URLLoader
URLVariables
Here's a quick class I have made for you:
package
{
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.net.URLVariables;
import flash.net.URLRequestMethod;
import flash.events.Event;
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);
}
}
}
With this, you can send data to a given PHP script in the format of URLVariables.
URLVariables are easily prepared like so:
var vars:URLVariables = new URLVariables();
vars.myvar = "some value";
vars.myothervar = 30;
Here's a quick example I have mocked up for you which sends a string to PHP, then PHP sends back the string hashed as MD5 and also has a timestamp attached as a secondary value.
var php:PHPData = new PHPData();
var vars:URLVariables = new URLVariables();
vars.myvar = "marty";
php.send("http://projectavian.com/md5.php", vars);
Your output for this will be something similar to:
response: bb3761a33402b4f82806178e79ec5261
time: 1306133172
Just alter the _complete method in the PHPData class to handle your response data as required :)
I'll throw this in because your question has the mysql tag..
All you need to do is your standard INSERT and SELECT queries in the PHP script and encode your result into this format:
var=1&other=2&more=three
So you could have..
<?php
mysql_connect(/* ?? */);
mysql_select_db(/* ?? */);
// INSERT example
$thing = mysql_real_escape_string($_POST["thing"]);
mysql_query("INSERT INTO table VALUES('','$thing')");
// SELECT for response
$id = mysql_real_escape_string($_POST["uid"]);
$query = mysql_query("SELECT * FROM table WHERE id='$uid' LIMIT 1");
// send response
$r = mysql_fetch_assoc($query);
echo 'fname=' . $r["first_name"] . '&lname=' . $r["last_name"];
?>

Categories