Okay, here goes. I'm sure I'm only missing a small thing somewhere.
I'm trying to do a little Highscore System for my game and thus I have a php script on a webspace for the programm to access (I have literally 0 experience with php):
<?php
$json = json_encode($_REQUEST);
$fileSave = fopen("processdata.txt", "a+") or die ("Can't create processdata.txt");
fwrite($fileSave, $json);
fclose($fileSave);
print($json);
?>
processdata.php
then, in actionscript, I juse this code to access the file and parse it:
//set variables to send to the php script
var variables:URLVariables = new URLVariables();
variables["name"] = "Player1";
variables["points"] = 123;
//set request to load php script
var request:URLRequest = new URLRequest("processdata.php");
request.method = URLRequestMethod.POST;
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, httpRequestComplete);
loader.load(request);
//php script finished
function httpRequestComplete(_e:Event){
//load processdata.txt
var uLoader:URLLoader = new URLLoader();
var uReq:URLRequest = new URLRequest("processdata.txt");
uLoader.addEventListener(Event.COMPLETE, getProcessdata);
uLoader.load(uReq);
}
//loading of processdata.txt finished
function getProcessdata(_e:Event){
var rawData : String = _e.target.data;
//convert the input string in readable JSON
rawData = rawData.split('"').join("\\\"");
rawData = "\"" + rawData + "\"";
//convert into JSON
var proData:Object = JSON.parse(rawData);
}
here is what processdata.txt looks like (for example)
{"name":"Player1","points":"123"}{"name":"Player2","points":"234"}
this is then converted in my AC into this (to make it readable for the JSON.parse):
"{\"name\":\"Player1\",\"points\":\"123\"}{\"name\":\"Player2\",\"points\":\"234\"}"
Now, how to I access the parsed JSON String? I tried all of those and nothing works:
proData.name;
proData[name];
proData["name"];
proData[0];
proData[name[0]];
for (var obj : String in proData){
obj;
}
Any help is appreciated. Doesn't matter where you find a possibility to make this work (PHP, AC3, JSON, etc)
Also, if you have a simple possibility for me to change my php in a way that it creates xml instead of php, I can do the rest from there, I get my Code to work with a XML File.
Thanks in advance.
You should know that your JSON content is not valid and that's why you can get nothing from it in the ActionScript side.
As you are saving players scores, you can store your data as an array :
[
{
"name": "Player1",
"points": "123"
}, {
"name": "Player2",
"points": "234"
}
]
but to get that, you've to edit your PHP code like this, for example :
<?php
$json_file = 'scores.json';
$new_score = $_REQUEST;
if(file_exists($json_file))
{
// get stored scores
$scores = json_decode(file_get_contents($json_file));
} else {
// create an empty array to store scores
$scores = array();
}
// add the new score to scores array
array_push($scores, $new_score);
// persist scores array as json content
file_put_contents($json_file, json_encode($scores));
?>
then in the ActionScript side, you can do :
function getProcessdata(e:Event) : void
{
var rawData:String = e.target.data;
var data:Array = JSON.parse(rawData) as Array;
for(var i:int = 0; i < data.length; i++){
trace(data[i].name); // gives for example : "Player1"
}
}
Hope that can help.
Related
I'm trying to send data to a PHP file via JSON but i'm getting an error when trying to JSON the data.
I'm pretty sure i'm doing this right. Any suggestions ?
Here's my ActionScript 3 code :
var dataToSend:Array = new Array();
var data:Object = new Object();
data.callFunction = "getQuestion";
data.numberOfQuestions = "1";
dataToSend.push(data);
trace(data);
var variables:URLVariables = new URLVariables();
variables.data = JSON.stringify(dataToSend);
var url:String = "myurl";
var request:URLRequest = new URLRequest(url);
request.method = URLRequestMethod.POST;
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.load(request);
loader.addEventListener(Event.COMPLETE, requestComplete);
And my PHP code :
if $data[ "callfunction" ] = "getQuestion";
{
echo("Sent");
}
Your ActionScript 3 code looks fine but you have some problems in your PHP's one.
Let's see that.
The if statement in PHP is like the AS3's one :
<?php
if( condition )
instruction;
?>
The equality operator is the == and not the assignment one ( = ).
As you have sent your data using the POST method, you can use the PHP's $_POST array to get it.
Then, as you have sent it on JSON format, you can decode it using the decode_json() function in your PHP side.
So your PHP code can be like this for example :
<?php
if(isset($_POST['data']))
{
$data = $_POST['data'];
$json_data = json_decode($data);
if($json_data[0]->callFunction == "getQuestion")
{
echo("Sent");
}
}
?>
Then you can get the response of your PHP script in your AS3 requestComplete function :
function requestComplete(e:Event): void
{
trace(URLLoader(e.target).data); // gives : Sent, for example
}
...
Hope that can help.
I have working with amcharts (line charts). Set data dynamically with ajax and get the data from php code in JSON format.
Problem comes string is not changed to array dynamically.
if i have add this string static in jquery code
code:
[{"country":"17 Feb","visits":"4","color":"#EA5759"},{"country":"16 Feb","visits":"1","color":"#EA5759"},{"country":"15 Feb","visits":"3","color":"#EA5759"}];
Thats working fine.
if i have set this code dynamically. line charts shows undefined.
i have use this function
ajax return code
[{"country":"17 Feb","visits":"4","color":"#EA5759"},{"country":"16 Feb","visits":"1","color":"#EA5759"},{"country":"15 Feb","visits":"3","color":"#EA5759"}]
i have just pass this on this function. like
var ajaxString = [{"country":"17 Feb","visits":"4","color":"#EA5759"},{"country":"16 Feb","visits":"1","color":"#EA5759"},{"country":"15 Feb","visits":"3","color":"#EA5759"}];
and call this funciton
lineChart(ajaxString);
function lineChart(data) {
var chart;
var chartData=data;
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "country";
chart.startDuration = 1;
// AXES
// category
var categoryAxis = chart.categoryAxis;
categoryAxis.labelRotation = 45; // this line makes category values to be rotated
categoryAxis.gridPosition = "start";
// value
var valueAxis = new AmCharts.ValueAxis();
valueAxis.dashLength = 5;
// valueAxis.title = "Visitors from country";
valueAxis.axisAlpha = 0;
chart.addValueAxis(valueAxis);
// GRAPH
var graph = new AmCharts.AmGraph();
graph.valueField = "visits";
graph.colorField = "color";
graph.balloonText = "<b>[[category]]: [[value]] Users</b>";
graph.type = "column";
graph.lineAlpha = 0.2;
graph.fillAlphas = 0.9;
chart.addGraph(graph);
// CURSOR
var chartCursor = new AmCharts.ChartCursor();
chartCursor.cursorAlpha = 0;
chartCursor.zoomable = false;
chartCursor.categoryBalloonEnabled = false;
chart.addChartCursor(chartCursor);
chart.creditsPosition = "top-right";
// WRITE
chart.write("chartdiv");
}[![undefined message][1]][1]
But thats not working.
Thank You in advance
The ajaxString that you are passing to your function is simply an string and not a json object , so what your function lineChart might be expecting is json object so try to convert your ajaxString into valid json object before sending it to your function using
JSON.parse(ajaxString);
This looks like you are attempting to set a JSON string to chartdata instead of a javascript object array.
In this case, you should try to parse your string gotten through the ajax call like so : JSON.parse(dataelement) before setting it to chartdata.
You can create the code dynamically in PHP and covert the array in json via json_encode.
encoded json can be used later in the jquery.
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.
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);
i have a php script that print with echo this:
'&string="tom,dick,harry"'
and i need to put the "tom,dick,harry" in an actionscript string, that i have to split in an array. I'm having problems reading the php output, i'm using the URLLoader and TheURLVariables Classes in this way
var myRequest:URLRequest = new URLRequest("ip/directory/script.php");
var myLoader:URLLoader = new URLLoader();
function onLoaded(event:Event):void {
var variables:URLVariables = new URLVariables( event.target.data );
modelli = variables.string.split(",");
caricaColori(modelli[0]);
}
myLoader.addEventListener(Event.COMPLETE, onLoaded);
myLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
myLoader.load(myRequest);
What am i doing wrong?
Thought that you got problem with URLVariables, I still not totally understand this yet
function onLoaded(event:Event):void {
var variables:URLVariables = new URLVariables( event.target.data );
modelli = variables.string.split(",");
caricaColori(modelli[0]);
}
why do you need to store it into a URLVariables instance? Why don't parse it directly. If you are afraid of the "&string=", you don't need to echo it on PHP side, or can slice it out on Actionscript side.
modelli = event.target.data.split(",");
Perhaps using a variable name that isn't reserved might help. string seems like a bad choice.
// in php change
echo '&string="tom,dick,harry"'
// to
echo "tom,dick,harry"
// in actionscript change
function onLoaded(event:Event):void {
var str:String = event.target.data;
modelli = str.split(",");
caricaColori(modelli[0]);
}
If you want to add more variables and whatever, I would suggest turning the php response into an xml file. URLVariables should be used to SEND data to the server not for parsing a server response.
LOOK HERE
function onLoaded(event:Event):void {
var variables:URLVariables = new URLVariables( event.target.data );
modelli = variables.string.split(",");
caricaColori(modelli[0]);
}
Your problem is that you're loading the variables into a URLVariables container, and then trying to call a string function on it. I would do it this way instead:
function onLoaded(event:Event):void {
//load data as a string
var variables:String = event.target.data;
//make a new array
var modelli:Array = new Array();
modelli = variables.split(",");
//possibly pop the array
modelli.pop(); //pop off the last empty element of array
caricaColori(modelli[0]);
}
There's also a good chance that when you load this PHP data, you'll need to pop() the last element off of the array because it will be an empty string.