I want to be able to send complex data from Flex to PHP and be able to parse that data via PHP script. I'm able to send a basic key value pair object but anything more complex than that doesn't translate accordingly.
This works...
ht.send({label:"FOO", label2:"FAA", label3:"FII", label4:"FEE"});
It translates as expected
This doesn't work...
ht.send({obj11:{label:"FOO", label2:"FAA"}, obj2:{label3:"FII", label4:"FEE"}});
It is posted as a string [object][object].
Is it possible to send complex data to PHP? I've tried JSON.encode(object). Do I need to send XML instead?
I believe Json didn't work because you didn't set it up correctly
var myComplexObject:Object ={obj11:{label:"FOO", label2:"FAA"}, obj2:{label3:"FII", label4:"FEE"}}
var dataToSend:Object = { data: JSON.encode(myComplexObject) }
ht.send(dataToSend);
// on the php side you will have something like so
$data = json_decode( $_POST['data'] );
echo '<pre>';
print_r( $data );
I would highly recommend using AMF instead of JSON, given it's native support in Flex.
If you are working with large datasets, I have found AMF more effective, but at the end of the day it boils down to what you're most comfortable with. AMF will be easier to work with in Flex, though.
Interesting reads:
http://web.archive.org/web/20090129160211/http://www.5etdemi.com/blog/archives/2006/12/clearing-the-fud-on-amfphps-speed-versus-json-and-xml/
http://web.archive.org/web/20090210160254/http://blogs.adobe.com/mikepotter/2006/07/php_and_flex_js.html
Related
i'm searching the inet for around 3 days now and i'm stuck at this.
I got a MySQL Database and a php Script, as well as a Game made in UE4.
UE4 uses c++.
So now i want to send requests from the c++ game to the php script and that shall interact with the database.
For example create an account or login. I also want to pass the mysql query result of the php script to my c++ class.
I tried using HttpRequest, but i can't get data from php to c++ with that.
Maybe you can, but i don't understand it at all.
What i accomplished by now is that you can send a POST request from the game to the php script and pass variables so that the script uses them to perform the mysql query.
But how can i pass data from the php file to c++ now? The response i get is always the whole site (head and body) and i don't know where i could save the query result to pass it to the c++ code.
I'm a full beginner here, so go easy on me. I read so many different posts and blogs that my brain hurts like hell ): I hope someone can tell me how to do this easily or at least give me a hint on what i have to google and what i could use. I don't need a full tutorial, just a name of a library better than the Http.h (if simple HttpRequest cant manage this) would be enough. ): I'm really frustrated...
eXi
The PHP script should retun a HTTP response reduced to a bare minimum. It doesn't even need to be a HTML document:
<?php
// file: api.php
$param = $_POST['myparam'];
$foo = bar($param); // $foo contains e.g. "1,ab,C"
echo $foo; // if you opened http://myhost.com/api.php in a browser
// all you would see is "1,ab,C"
// (which is not a valid HTML document, but who cares)
?>
Then parse this HTTP response (a plain string, that is) from your game. You can use your own data format, or use a well-known format of your choice (XML or JSON are good candidates).
The json object in unreal is pretty good, so I would recommend outputting json from your php script. Json in php is a pretty natural workflow.
<?php
$obj['userid'] = 5476;
$obj['foo'] = 'bar';
echo json_encode($obj);
php?>
That will echo out
{"userid":5476,"foo":"bar"}
If that's all you output in your script then it's pretty straightforward to treat that as a string and populate an unreal json object with it.
FString TheStuffIGotFromTheServer;
TSharedPtr<FJsonObject> ParsedJson;
TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(TheStuffIGotFromTheServer);
if (FJsonSerializer::Deserialize(JsonReader, ParsedJson))
{
FString foo = ParsedJson.GetStringField("foo");
double UserId = ParsedJson.GetNumberField("userid");
}
Check out the unreal json docs to get a feel for what you can do with it.
I'm using HTTPful to send some requests in PHP and get data in JSON, but the library is converting the result into objects, where I want the result to be an array. In other words, its doing a json_decode($data) rather than json_decode($data, true).
There is, somewhere, an option to use the latter, but I can't figure out where. The option was added in v0.2.2:
- FEATURE Add support for parsing JSON responses as associative arrays instead of objects
But I've been reading documentation and even the source, and I don't see the option anywhere... The only way I can think of is making my own MimeHandlerAdapter which does a json_decode($data, true) but it seems like a pretty backwards way of doing it if there is an option somewhere...
It may be a little late to answer this, but I did a little research while using Httpful and found the answer. Httpful uses a default set of handlers for each mime type. If one is registered before you send the request, it will use the one you registered. Conveniently, there is an Httpful\Handlers\JsonHandler class. The constructor takes an array of arguments. The only one it uses is $decode_as_array. Therefore, you can make it return an array like this:
// Create the handler
$json_handler = new Httpful\Handlers\JsonHandler(array('decode_as_array' => true));
// Register it with Httpful
Httpful\Httpful::register('application/json', $json_handler);
// Send the request
$response = Request::get('some-url')->send();
UPDATE
I realized that it sometimes parses the response into a funky array if you don't tell the request to expect JSON. The docs say it's supposed to work automagically, but I was having some issues with it. Therefore, if you get weird output, try explicitly telling the request to expect JSON like so:
$response = Request::get('some/awesome/url')
->expects('application/json')
->send();
I never used this library. But in a research I found that you can find this option at src/Httpful/Handlers/JsonHandler.php on line 11.
There you will see:
private $decode_as_array = false;
And this flag is used at the same file on line 27:
$parsed = json_decode($body, $this->decode_as_array);
You have to set decode_as_array to true value, to do this:
\Httpful\Httpful::register(\Httpful\Mime::JSON, new \Httpful\Handlers\JsonHandler(array('decode_as_array' => true)));
before Request::get calling
I'm passing a JSON object from flash AS3 to PHP, which is then taken apart and passed to the DB.
In Flash:
var jsonObject:Object = JSON.encode(currentlySelectedArray);
In PHP:
$json_pieces_array = $_POST['jsonArray'];
$json_obj = json_decode($json_pieces_array, true);
When I test my code by copy/pasting the output of 'trace (saveDataJSON.ToString());' and putting it into my '$_POST['jsonArray'] = '[[Valid JSONLint checked JSON here.]]', everything works fine and it gets pushed to the database.
But when I don't meddle and use the flash-sent $_POST, nothing pushes to the MYSQL DB.
My question is twofold:
1) What's the best way to bug test this sort of complication? I'm in the Flash interface.
2) What sorts of things should I be looking for? I already checked that the JSON being encoded was valid. Is there some sort of weird typecasting I'm missing?
At first you have to debug request from flash. You can do it in several ways:
create dummy file that does var_dump($_REQUEST);;
add file_put_contents('my_dump_file.txt', var_export($_REQUEST, true)); in existing script;
check your webserver logs;
debug you script with debugger (xdebug or similar).
Then you should check your PHP script. Try to var_dump($_REQUEST); on the top and exactly before json_decode. It can be so that $_POST['jsonArray'] is overwritten somewhere else.
I guess that the problem is between flash and php. In most cases there is simply misspelling or $_POST is mixed with $_GET.
I've been doing a lot of things that include making AJAX requests to get information from the backend of my site when i had an interesting question. Is it better to do the html styling in php, then send to the client, or is it better to send the data as json and then style in javascript?
Since this question is kind of vauge i'll give an example:
<?php
$data = array();
$data[0] = array("username" => "Supericy", "content" => "just a sample message 1");
$data[1] = array("username" => "Supericy", "content" => "just a sample message 2");
$data[2] = array("username" => "Supericy", "content" => "just a sample message 3");
// etc...
// now this is the choice:
if ($json)
{
return json_encode($data);
}
else
{
// or
$returnString = "";
for (...)
{
$returnString .= '<div class="username">' . $data[i]["username"] . '</div>';
$returnString .= '<div class="content">' . $data[i]["content"] . '</div>';
}
return $returnString;
}
?>
And then in my javascript:
// get the information as raw json
var data = ajax_request(json = true);
var author = document.createElement('div');
author.className = "author";
author.innerHTML = data[i]["username"];
var content = document.createElement('div');
content.className = "content";
content.innerHTML = data[i]["content"];
body.appendChild(author);
body.appendChild(content);
// -- OR --
// get the information as pre-formated html
var data = ajax_request(json = false);
body.innerHTML += data;
As other users have stated, it depends greatly on who your intended audience is. If you are trying to keep startup costs low and are developing for users who generally have a cable / constant internet connection, then you can do whatever floats your boat.
However, if you are designing application and would like it to remain relatively maintainable, you should probably look into JSON. If you do go with JSON, I would also suggest your pick up a javascript library like jQuery so that you can safely and easily handle decoding of the JSON object.
In fact, anymore, even when I am returning HTML from the AJAX page, I still wrap it in a JSON object. It seems a bit more standardized that way and I can easily reuse my previous javascript code.
Here are some basic tradeoffs:
Sending HTML Straight from PHP
HTML code is visible in the code and may be easier to find validation issues.
May be easier to maintain. (Key word MAY.) If you are generating complex html, it might be easier to build in PHP.
Sending JSON to PHP and letting Javascript Convert to HTML
Less data sent to browser. This is a big plus for mobile users who are on limited connections and pay for their bandwidth usage.
Generally more maintainable.
Lets the clients computer do the processing rather than the server (reduces server load).
Appears to be a standard format for communication with a server these days. Even Google Maps API uses JSON to interact with developers. You might even consider JSON the new XML.
By the way JSON stands for Javascript Object Notation. It follows the standard syntax for objects in javascript:
For example: var blah = {'variable_name':'variable_value'};
So my answer to you would be to use JSON, no matter what, but who your viewer is should determine how much data you are sending.
For extremely simple sites/examples it doesn't matter... for larger projects I would go with always having a json response which is more portable.
Using json makes both the server call and js view logic reusable.
JSON would be my preference. It's much easier to work with HTML properly in JavaScript, and PHP's json_encode is ever so convenient. Plus, it gives a nice, clean MVC feel.
I like back end styling because then you dont have to worry about browser compatibility (ie interent explorer).
spent a few hours trying to figure this out, but cannot for the life of me figure out what's going wrong.
All I'm trying to do is load this:
https://recruit.zoho.com/ats/EmbedResult.hr?jodigest=2cV.Sr2As6VxhLMxQGuTNij*g.Fb3J7ysduDs.AC9sU-&atslocale=en_GB&rawdata=json
which I believe is json, into either javascript/jquery or php and use the data.
I've looked into jsonp, followed some tutorials, used some demos as templates and just can't get the above data to work.
If anyone can shed some light it would be much appreciated. It really shouldn't be this complicated, but I don't know what's going wrong.
Yep, that's JSON. The site may not support JSONP, so you're gonna have to use PHP to do this.
This is untested, but should work.
<?php
$url = 'https://recruit.zoho.com/ats/EmbedResult.hr?jodigest=2cV.Sr2As6VxhLMxQGuTNij*g.Fb3J7ysduDs.AC9sU-&atslocale=en_GB&rawdata=json';
$JSON = file_get_contents($url);
// echo the JSON (you can echo this to JavaScript to use it there)
echo $JSON;
// You can decode it to process it in PHP
$data = json_decode($JSON);
var_dump($data);
?>
JSONP relies on the server to return a JSONP formatted response. Basically, to use JSONP the server needs to return a JSON string wrapped in a function invocation ({"foo":1} becomes func({"foo":1})).
As the server your using doesn't return a JSONP response, you cannot use JSONP, you can only use JSON.
This is a shame, as JSON cannot be used x-domain due to the same origin policy (SOP). Therefore, the only option you have is to use a proxy server, which retrieves the JSON from the server, and either gives it to you in JSONP (see Yahoo Pipes), or which is on the same domain as the requested page (write a simple PHP script to get the file using file_get_contents() and then echo the output), in which case it can return the JSON.
I breifly looked at the requirements and it looks like you need an API key as well as an account. I saw that the site provides services for XML and JSON only. It looks to be fairly well documented.