(AS3 & PHP) sending multiple values from php to flash - php

I'm trying to send multiple values from PHP to Flash. I know how to send back one value, and that's by using PHP's print or echo, and then in flash using e.target.data., for example...
PHP:
print "resultMessage=$something";
Flash:
var resultText:TextField;
resultText.text = e.target.data.resultMessage;
The problem is when trying to receive 2 values; I've tried things like...
PHP:
print "resultNumber=$somethingNumber";
print "resultName=$somethingName";
Flash:
var flashNumber:TextField
flashNumber.text = e.target.data.resultNumber;
var flashName:TextField;
flashName.text = e.target.data.resultName;
But when I try that, flashNumber would end up as flashNumber and flashName mashed together, like 2Tom or 7Mary or something like that.
I tried printing <br> between the 2 values in PHP, but I still got the same result. I know that I can split the PHP into 2 PHP files and get a value from each one, but that would be a little ridiculous, since in my program I'll need to get many values.
Is there another way to send values from PHP to Flash, so that I can send more than 1 value? Or, is there a way to use print or echo to send more than 1 value?
Thank you very much in advance.

You can do this by outputting your data in a standard URL encoded variable format. (You need the ampersand that applications use to separate variables - otherwise it thinks everything after the first = is the value)
eg: print "resultNumber=$somethingNumber&resultName=$somethingName";
Then AS3 should automatically work the way you are trying.
You could also ouput XML or JSON as suggested by someone else.
JSON
PHP
<?php
$arr = array(somethingName, somethingNumber);
echo json_encode($arr);
?>
AS3
var jsonObj = JSON.parse(e.target.data);
trace(jsonObj.somethingName, jsonObj.somethingNumber);
XML
PHP
<?php
$string = <<<XML
<data>
<somethingName>
blah blah blah
</somethingName>
<somethingNumber>
12345
</somethingNumber>
</data>
XML;
$xml = new SimpleXMLElement($string);
echo $xml->asXML();
?>
AS3
myXML = new XML(e.target.data);
trace(myXML.somethingName, myXML.somethingNumber);

Better use some data formatting instead of passing data as pure text - XML or JSON is a good idea.

Related

Retrieve string from json

I'm trying to retrieve a URL string from some json code.
Here is the json code
{"files":["www.example1.com"],"previews":["www.example1preview.com"],"meta":{},"userId":"guest","product":{"id":"2335","name":"standard"},"type":"u"}
Looking at what I've seen in the PHP manual I'm trying to retrieve previews like this.
<?php
ob_start();
include('getjson.php');
$meta_value_json = ob_get_clean();
echo $meta_value_json;
$meta_value_json = json_decode($meta_value_json);
print $meta_value_json->{'previews'};
?>
This doesn't seem to output the value however.
By experimenting with php -a command on terminal, I've put your json into json_decode and managed to get your link by just doing:
print $meta_value_json->previews[0];
The only reason to use print $meta_value_json->{'previews'}; at least according to php documentation is if you want an object as output and the key trying to retrieve is numerical or of a type that is not supported by php.
By experimenting a bit further, the reason that print $meta_value_json->{'previews'}; fails is because print expects a string, in our case here previews is an array. Therefore if you do print $meta_value_json->{'previews'}[0]; it will also work as expected.
You need to get the value from your decoded json like this: $class->parameter.
Knowing that previews is an array, you will also need to choose a specific element from it to print ( I got the first one ):
<?php
ob_start();
include('getjson.php');
$meta_value_json = ob_get_clean();
echo $meta_value_json;
$meta_value_json = json_decode($meta_value_json);
print $meta_value_json->previews[0]; /// get the specific value
?>

convert query String to json in php

I send a QueryString formatted text like bellow to a php Script via Ajax:
title=hello&custLength=200&custWidth=300
And I want to convert this text to a JSON Object by this result in PHP:
{
"title" : "hello",
"custLength" : 200,
"custWidth" : 300
}
How can i do that. Does anyone have a solution?
Edit :
In fact i have three element in a form by title , custLength and custWidth names and i tried to send these elements via serialize() jquery method as one parameter to PHP script.
this code is for Send data to php:
customizingOptions = $('#title,#custLength,#custWidth').serialize();
$.post('cardOperations',{action:'add','p_id':p_id,'quantity':quantity,'customizingOptions':customizingOptions},function(data){
if (data.success){
goBackBtn('show');
updateTopCard('new');
}
},'json');
in PHP script i used json_encode() for convert only customizingOptions parameter to a json.
But the result was not what I expected and result was a simple Text like this:
"title=hello&custLength=200&custWidth=300"
I realize this is old, but I've found the most concise and effective solution to be the following (assuming you can't just encode the $_GET global):
parse_str('title=hello&custLength=200&custWidth=300', $parsed);
echo json_encode($parsed);
Should work for any PHP version >= 5.2.0 (when json_encode() was introduced).
$check = "title=hello&custLength=200&custWidth=300";
$keywords = preg_split("/[\s,=,&]+/", $check);
$arr=array();
for($i=0;$i<sizeof($keywords);$i++)
{
$arr[$keywords[$i]] = $keywords[++$i];
}
$obj =(object)$arr;
echo json_encode($obj);
Try This code You Get Your Desired Result
The easiest way how to achiev JSON object from $_GET string is really simple:
json_encode($_GET)
this will produce the following json output:
{"title":"hello","custLength":"200","custWidth":"300"}
Or you can use some parse function as first (for example - save all variables into array) and then you can send the parsed output into json_encode() function.
Without specifying detailed requirements, there are many solutions.

Echo array into string, not showing array map [duplicate]

I have this php code
<?php
$status_code=1;
echo "<?xml version=\"1.0\"?>\n";
echo "<response>\n";
echo "\t<status>$status_code</status>\n";
echo "\t<time>" . time() . "</time>\n";
if ($status_code == 1) {
echo "\t<message>\n";
echo "\t\t<author>Vlad</author>\n";
echo "\t\t<text>Ova e poraka</text>\n";
echo "\t</message>\n";
}
echo "</response>";
?>
Why I don't get the printed xml code in browser?
Also is it good practice to create ajax requests by printing the xml code directly in php or should I use some xml php function to create xml code?
I wanted to create a chat system by using jquery, ajax, php and mysql using this tutorial, but I get error that the above printed xml is not well formed
Try viewing your source, the xml is there but just not visible. Your browser will try to show the page as HTML, since you dont supply the correct headers. Since there are no tags, you wont see anything.
You should send the correct headers, as such:
header('content-type: text/xml')
As the others have said, you need to give the browser a header to let it know how to display the page.
As for xml functions, have a look at the PHP SimpleXMLElement
you have to put header (to let the browser know how to render the display):
header ("Content-Type:text/xml");
You have to use proper content-type, as the others have said.
I recommend you to use XMLReader.
Or if you want a n easier way, then try to use Heredoc string syntax with sprintf and htmlspecialchars to encode values with characters that have special meanings in XML (like <>&)

Beginner to creating and reading JSON objects

Using http://objectmix.com/javascript/389546-reading-json-object-jquery.html as a starting point, I have been reading lots about JSON. Unfortunately I am a total beginner and can't get my head around the basics of creating JSON objects.
I have created a PHP page called getContact.php
<?php
"Contact": {
"ID" : "1",
"Name" : "Brett Samuel"
}
?>
And a javascript file with the following code:
$.getJSON('getContacts.php', function(data) {
var obj = (new Function("return " + data))();
alert(data.Contact.Name)
});
This page http://msdn.microsoft.com/en-us/library/bb299886.aspx suggests I have the basic approach correct. Can anyone tell me why this does not work? Absolutely nothing happens.
Thanks in advance.
Your PHP file contains JSON, which is not valid PHP, and will therefore error.
If you're working with PHP the easiest way to build JSON is to first prepare your data as an array (associative or indexed, as required) then simply convert it via json_encode(). (You can also decode JSON, with the corresponding json_decode().
[EDIT - in response to comment, just have a look at the PHP docs for json_encode() - it's very self explanatory. You take an array, pass it to json_encode(), and you get a JSON string.
$arr = array('one', 'two', 'three');
echo json_encode($arr); //JSON string
JSON is not a programming language, and it's certainly not executable as PHP. It's just a file format. If you want your web server to serve up a static JSON file, just drop it in the file system as filename.json, without any <?php tags. (Of course, as with HTML, you can also make it a .php file and just not have any PHP in it, other than something to set the Content-Type since the file suffix won't do it automatically. But that's wasteful.)
If you want to dynamically generate some JSON with PHP, then you have to write PHP code to print it out, e.g.:
<?= json_encode( array(
'Contact' => array('ID' => 1, 'Name' => 'Brett Samuel' )
) ); ?>
Also, note that a JSON document has to be a complete object; yours requires another set of curly braces around the whole thing (as output by the above snippet).
you need to use json_encode and json_decode
refer this json php manual

json_encode won't escape newlines

Firstly, I have search Stack Overflow for the answer, but I have not found a solution that works.
I am using an MVC framework (yii) to generate some views and throw them in an array. Each view is a card, and I have an array of cards ($deck) as well as an array of arrays of cards ($hands, the list of hands for each player). I'm simply trying to set a javascript variable on the front-end to store the hands created in PHP. My view has, it is worth noting, multiple lines. In fact, my current test view consists only of:
test
test
I therefore used json_encode, but it's giving me the following error when I use $.parseJSON():
Uncaught SyntaxError: Unexpected token t
I read elsewhere that it is required (for whatever reason) to use json_encode twice. I have tried this, but it does not help.
With a single json_encode, the output of echoing $hands (followed by an exit) looks pretty healthy:
[["test\ntest","test\ntest","test\ntest","test\ntest", etc...
But when I do not exit, I get a syntax error every time.
Edit: Here is a sample of my code. Note that $cards is an array of HTML normally, but in my simplified case which still errors, includes only the two lines of 'test' as mentioned above.
$deck = array();
foreach ($cards as $card) {
$deck[] = $this->renderPartial('/gamePieces/cardTest',
array('card'=>$card), true);
}
$hands = Cards::handOutCards($deck, $numCards , $numPlayers);
$hands = json_encode($hands);
echo $hands; exit;
With JavaScript, I am doing the following:
var hands = $.parseJSON('<?php echo json_encode($hands); ?>');
It errors on page load.
Any help would be appreciated!
Thanks,
ParagonRG
var hands = $.parseJSON('<?php echo json_encode($hands); ?>');
This will result in something like:
var hands = $.parseJSON('{"foobar":"baz'"}');
If there are ' characters in the encoded string, it'll break the Javascript syntax. Since you're directly outputting the JSON into Javacript, just do:
var hands = <?php echo json_encode($hands); ?>;
JSON is syntactically valid Javascript. You only need to parse it or eval it if you receive it as a string through AJAX for instance. If you're directly generating Javascript source code, just embed it directly.

Categories