JSON concept with javascript & PHP - php

I need someone to shed some light on this subject.
When a person do an AJAX call, that call a php script which echo out json_encode stuff, so that the javascript can mess around with it. Note: Assuming we set the header to json in the php script.
The data that the javascript receive from the php script, do we have to parse it using eval or json's library? Edit: Is it because it treats the data recieved from the php file as text and not as javascript?
Can we use the javascript dot-notation on the data that the php script returned? Or does this data have to some how be converted to a javascript object before we can use dot-notation?
Thank you in advance.

JSON is merely a string, which happens to conform to Javascript's syntax for objects (hence the abbreviation: JavaScript Object Notation.)
To convert it to a Javascript object, you can use the eval function, but for greater security, it's recommended to use the JSON object included in modern browsers, or a function provided by your Javascript library of choice:
var json = '{"thing":1, "thang":"two"}';
var obj1 = eval('('+json+')'); // easier, less secure
var obj2 = JSON.parse(json); // secure, but doesn't work everywhere
var obj3 = jQuery.parseJSON(json); // secure, works everywhere
Many libraries will also handle the conversion for you as part of the Ajax request. Here's how jQuery does it:
jQuery.get('http://domain.com/path/to/request', function(obj)
{
// string is automatically converted to an object,
// usable as array or with dot notation
alert(obj.thing);
alert(obj['thang']);
},
'json'); // indicates that we are requesting json and not html

You can always use a library like jQuery, Mootools, Prototype, etc. for the decoding JSON text to Javascript variables..

JSON is something like serialize from PHP :) It's a way to transform string to object and back :)

Related

Difference between echoing json_encode and returning it in ajax

I think this may be classified as basic but I was curious. Why do you have to parse json encoded data returned from ajax calls but not if it is echoed by php in the main loading document?
Edit: Basically the question is, if I have an object called data with a property id in both cases, why I can type
data.id
and have the value returned when the json object has been echoed out while loading the main document, but have it throw an error when returned from an ajax call and not parsed?
By echoed, I assume you mean you did something like this:
<script>
var data = <? echo json_encode($data) ?>;
alert(data.id);
</script>
If that's the case, the browser knows that the echoed json is code because it's contained by script tags. JSON is a subset of JavaScript, so what you're really doing here is generating JavaScript code that the browser then interprets.
Ajax, on the other hand is different. When you load something with ajax, it might be text, xml, csv, html, svg, or any of dozens of different formats. JSON is just a data format like all the others I listed, so you've got to tell the javascript engine what it is. That's why you have to parse it. It needs to know the format of the text so it can interpret it correctly.
You don't have to, and JSON-encoded strings still need to be "decoded" from Javascript. It's just a faster way of being able to access array elements/properties in the returned string for ajax calls.

JSON - proper way to decode string in JavaScript

I'm wondering what would be the best way to decode JSON string inside Javascript code.
I want my json string to be embeded inside my JS, like this:
var params = dojo.fromJson('<?=json_encode($this->params); ?>');
dojo.fromJson decodes my string and json_encode is a php function that encodes an object on the server side.
It seems that json encoder ignores ' chars and only converts " to \". So when one of my variables inside $this->params contains a ' character there is a Javascript error.
For example:
var params = dojo.fromJson('{"id":"11","object_type":"Let's go"}');
What is the best way to approach this ?
Thanks for help.
Since you are producing the JSON yourself, you can trust it, so you don't need to treat it as JSON and can treat it as JS instead.
var params = <?=json_encode($this->params); ?>;
PHP's JSON encoder will escape </script> for you so you don't need to worry about terminating your script element with your data.

JSON Encode/decode doesn't work as it should

I am preparing and sending a JSON string from my PHP file to my Javascript function like this:
$json = array();
$json['slice'] = false;
$json['G500'] = false;
$json['KG1'] = false;
$encoded = json_encode($json);
die($encoded);
However, in my JS function, if I do this, it is unable to decode the JSON object:
var d = req.responseText;
var jsonObject = eval(d);
The only way, I can get it to eval the JSON object is by adding parentheses manually
jsonObject = eval("(" + d + ")");
I have the same problem going in reverse as well. Sending a JSON object to PHP and trying to decode it there fails. I believe I would need to remove the parentheses in my PHP script before attempting to decode.
Why is this happening? Is there something I can do to work around this incompatibility?
EDIT:
PHP to JS is now working if I use JSON.parse. I'm still having trouble the other way around.
This is how I'm sending the data to the PHP:
var JSONstring =
{
"Product": document.getElementById('item').value,
"Size": document.getElementById('size').value,
"Quantity": document.getElementById('quantity').value
};
url = "maintainOrder.php?json=" + JSON.stringify(JSONstring);
req.open("GET", url, true);
However, the PHP script is unable to decode it.
$newItem = json_decode($_GET['json']);
array_push($_SESSION['order'],$newItem);
Your Javascript
eval has an issue with leading { characters, because of an ambiguity with block scope.
Using the parentheses to force the input to be parsed as an expression is a solution, but you should avoid eval entirely and use a proper JSON decoding function.
Your PHP
We'd need to see the data that you send to your PHP script to know why it won't parse. In general, as long as JSONLint accepts your JSON, so will PHP's json_decode. So give that a go.
For the php to javascript issue refer to the Tomalak Geret'kal answer.
For the javascript to php maybe I have the solution:
If you want an associative array in php then you have to pass assoc parameter as true into json_decode (default to false)
Example:
$array = json_decode($jsonString, true);
I was bitten a couple of times by this: by default json_decode try to create an object if it receive a javascript object (it make perfect sense if you think of) and you have to force it to render an associative array if you need this behaviour
I think you need to do some string processing, all you need to do is echo and see the exact format of your JSON string and make sure it conforms to the standard format, then use string processing both on the server and client sides to achieve the desired effect
Are you sure php is not adding slashes to the json text?, try saving the json text in a file in the server side to verify

printing a PHP string and parsing it as a JSON in javascript

I have a json_string in my database.
I echo and parse it to an object in javascript
I do
$.parseJSON('<?php echo $json_string;?>');
I get a json parse error.
What should I be doing?
This is my json_String
{"patches":[[{"diffs":[[1,"\u000a\u000a printhellon() {\u000a\u000a\u000a}d\u000a\u000a\u000a"]],"start1":0,"start2":0,"length1":0,"length2":26}],[{"diffs":[[0,") {\u000a\u000a\u000a}d"],[1,"s"],[0,"\u000a\u000a\u000a"]],"start1":15,"start2":15,"length1":11,"length2":12}],[{"diffs":[[0," {\u000a\u000a\u000a}ds"],[1,"d"],[0,"\u000a\u000a\u000a"]],"start1":16,"start2":16,"length1":11,"length2":12}]],"times":[1314489779299,1314489779408,1314489779581]}
I think JSON parsers don't like line breaks in strings for some reason. Parsing worked for me after removing the \u000a characters.
Edit: just like Brad said, it would be better to include the code directly as an object. Parsing JSON is usually more useful for data obtained using Ajax or something.
From your example, it appears like you're trying to insert PHP code into your javascript. You can't use PHP like that. PHP is server side, while Javascript runs in the browser after the page has been downloaded.
If you must get data from PHP to your javascript, you need to use AJAX. It's actually really easy with JQuery. Check out http://api.jquery.com/jQuery.ajax/

Show php print_r in Flash?

Trying to figure out a way to get ActionScript to print out a php object. In PHP, I can just do print_r, and I'm able to successfully get the object into Flash, but now can't figure out how to print out the object using ActionScript 3?
Well, when the request first comes over, there is always URLLoader.data, which is data in its raw form. If you're looking to get the data from a JSON-style object, there is for( var i:String in obj ). If you're looking for things more obscure than that, there is the ability to use describeType. My favorite example of the last one is in the JSONEncoder class.
From PHP, you can encode most objects to JSON using json_encode() (PHP5+). Using the AS3 JSON decoder from as3corelib you can then convert that encoded string into an oject that AS3 con read. After that you can iterate over the object as key/value pairs and output it however you wish.
I think I know what you mean, I had the same need, so I made this
http://www.actionscript.org/forums/showthread.php3?t=266979
scroll to the bottom, there is a description and an .AS file called trace_r that I wrote

Categories