I have an array of arrays in PHP in this layout for example,
"Key1" => { "id" => 1, "name" => "MyName", "address" => "USA" }
"Key2" => { "id" => 2, "name" => "MyName2", "address" => "Australia" }
The data in the PHP array was taken from SQL Database. Now I want to be able to use this in JavaScript.
I searched the web and people are suggesting to use JSON using this code:
var js_var = JSON.parse("<?php echo json_encode($var); ?>");
I get this error in firefox when using firebug
missing ) after argument list [Break On This Error]
var js_var = JSON.parse("{"Key1":{"id":"1","name":"MyName","address":"USA"...
Error is in right after JSON.parse("{"Key1
In google chrome, firebug does not report any errors
var js_var = JSON.parse('<?php echo json_encode($var); ?>');
Or, even better:
var js_var = <?php echo json_encode($var); ?>;
... Since JSON is, by definition, valid JavaScript syntax for object declaration.
Why go through this bizarre json_encode into a string to only JSON.parse on the client side? Useless use of encoding, really.
Try var js_var = <?php echo json_encode($var); ?>;
Your error is being cause by the fact you are using double-quotation marks (") to wrap the JSON string. Due to the fact that the JSON string also contains double-quotations the parser is unable to determine when the string starts and ends correctly.
Change the line to this:
var js_var = JSON.parse('<?php echo json_encode($var); ?>');
That been said JSON or JavaScript Object Notation is already a subset of the JavaScript programming language and therefore can already be parsed by the JavaScript engine so does not necessarily need to be parsed by JSON.parse.
var js_var = <?php echo json_encode($var); ?>;
I would however only recommend this option if you are sure about the JSON you are outputting as an incorrect parsing by JSON.parse can be handled where as incorrect JSON injected directly will cause a parser error I believe.
Related
I have a php variable which contain json, I use json_encode to transform an array to json.
If I print my var I have:
["L","M","M","J","V","S","D"]
But if I use my var in js I have:
["L","M","M","J","V","S","D"]
and I can't parse because I have an error
Uncaught SyntaxError: Unexpected token &
Is there a way to get json in my js ?
Thanks
Edit:
In php
$dayArray = array('L','M','M','J','V','S','D');
$dayArray = json_encode($dayArray)
In js
setDayArray('<?php echo $dayArray ?>');
setDayArray = function(dayArray){
console.log(dayArray);
}
With twig
calendar.setDayArray({{ dayArray }});
This is maybe due to symfony rendering, the only way I found is to do an ajax call using json header
To output JSON in PHP, output the result of passing your PHP structure through json_encode.
Example from the documentation:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Outputs:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Re your updated question, you've used
$dayArray = json_encode($dayArray)
setDayArray('<?php $dayArray ?>'); // Wrong
Get rid of the quotes, and include echo unless it's magically getting output some other way:
$dayArray = json_encode($dayArray)
setDayArray(<?php echo $dayArray ?>); // Right
When you do that, the browser will see something like:
setDayArray(["L","M","M","J","V","S","D"]); // Right
rather than
setDayArray('["L","M","M","J","V","S","D"]'); // Wrong
I find the solution
calendar.setDayArray({{ dayArray | raw }});
use raw to allow html
i have
$age = implode(',', $wage); // which is object return: [1,4],[7,11],[15,11]
$ww = json_encode($age);
and then i retrieve it here
var age = JSON.parse(<?php echo json_encode($ww); ?>);
so if i make
alert(typeof(<?php echo $age; ?>)) // object
alert(typeof(age)) //string
in my case JSON.parse retuned as string.
how can i let json return as object?
EDIT:
var age = JSON.parse(<?php echo $ww; ?>); // didnt work , its something syntax error
implode returns a string, so it is only natural that json_encode encodes it as such. It does not recognize already JSON-like data passed as a string.
If you want to get an object, you have to pass an associative array to json_encode:
$foo = array(
1 => 4,
7 => 11,
15 => 11
);
echo json_encode($foo); // {1:4,7:11,15:11}
With so little info about what $wage looks like before it's imploded, it's hard to tell exactly what you want to get. How is that structure ([1,4],[7,11],[15,11]) an object? Is the first element of each tuple a key? That's what I assumed with my example, but it might be off.
var age = [<?php echo $age; ?>];
a. You get a syntax error because you need to enclose the string within quotes, like so:
var age = JSON.parse("<?php echo $ww; ?>");
b. Moreover, you don't need JSON.parse. You can simply echo the php var after it was already json_encoded in the server side:
var age = <?php echo $ww; ?>;
JSON.parse is there to convert a JavaScript string to an object. In the case of PHP string, once it is built as JSON, echoing it in the right place is equivalent to coding it yourself.
i have encoded my required data in the json object ,but i want to decode the json object into a javscript array, my json encoded object is :
{"product_id":"62","product_quantity":"65"}
however i want to use this json in my java script and want it to be available to a java script array
so if i do :
var arr = new Array()
arr = <?php json_decode('$json_object',TRUE); ?>;
however when i check my page source i get null i.e arr =
how can i assign my json object converted to array to java script array ?
further how to access the json objects from java script array ?
json_decode returns a PHP data structure. If you want to serialise that to a JavaScript data structure you have to pass it through json_encode (and then actually echo the string that it returns).
Note that json_encode outputs a JavaScript data structure that is safe for injecting into a <script> element in an HTML document. Not all JSON is safe to do that with (PHP adds additional escape sequences, and will transform plain strings, numbers, null values, etc (which aren't legal JSON on their own).
Note that there is also no point in creating a new array and assigning it to arr if you are going to immediately assign something else to arr.
Also note that '$json_object' will give you a string starting with the $ character and then the name of the variable. Single quoted string in PHP are not interpolated.
var arr;
arr = <?php echo json_encode(json_decode($json_object,TRUE)); ?>;
Also note that this JSON:
{"product_id":"62","product_quantity":"65"}
Will transform in to a PHP associative array or a JavaScript object (which is not an array).
So given this PHP:
<?php
$json_object = '{"product_id":"62","product_quantity":"65"}';
?>
<script>
var arr;
arr = <?php echo json_encode(json_decode($json_object,TRUE)); ?>;
alert(arr.product_id);
</script>
You get this output:
<script>
var arr;
arr = {"product_id":"62","product_quantity":"65"};
alert(arr.product_id);
</script>
Which alerts 62 when run.
You could push the JSON objects into javascript array and iterate through the array, selecting the appropriate fields you need.
Fixed it..
var json = {"product_id":"62","product_quantity":"65"};
var array = new Array();
array.push(json);
for(var i = 0; i < array.length; i++){
console.log(array[i].product_id)
}
Okay so to start off :
the json string generated in PHP can be used in Javascript as an Object. If you declare the variable as an array to start with then it might conflict.
anyway this should work :
<?php
$error_fields_structure = array(
'product_id' => 4531
,'main_product_quantity' => 2
);
$json_object = json_encode($error_fields_structure);
?>
<html>
<head>
<script>
var jsonstring = <?php echo (isset($json_object) ? $json_object : 'nothing here'); ?>
for( var i in jsonstring ){
alert( i +' == ' +jsonstring[i] );
}
</script>
</head>
<body>
</body>
</html>
I'm looking for better and more robust solution for echoing out yepnope feature tests using php. The output should look something like :
{
test : Modernizr.geolocation,
yep : 'normal.js',
nope : ['polyfill.js', 'wrapper.js']
}
From an output like:
$l10n = array(
'test' => 'Modernizr.geolocation',
'yep' => "'normal.js'",
'nope' => array("'polyfill.js'", "'wrapper.js'")
);
Obviously, there is the issue of quotation marks being wrapped around the json object. I can't help but wonder if there's a different class altogether that caters to creating mixed javascript objects containing raw javascript as well as strings.
json_encode returns the JSON representation of a value, the point is JSON representation is not a javascript object, JSON is a subset of the javascript object literal, so you need to do the convert in javascript.
var l10n = <?php echo json_encode($l10n); ?>;
if (l10n.test === "Modernizr.geolocation") {
l10n.test = Modernizr.geolocation;
}
I'm using the combination of json_encode (PHP) and JSON.parser (Javascript from json.org) for passing a JSON object from PHP to Javascript, the JSON object may have quotes and double quotes so I'm using addslashes() function in PHP. This combination work well in Firefox but not in other browsers like Safari, Chrome or Internet Explorer. This is the code:
<?php
$json =array('n' => count($arrayEx), 'items' => array());
foreach($arrayEx as $item)
{
$json['items'][]=array( 'property1' => addslashes($item['property1']),
'property2' =>addslashes($item['property2'])
);
}
$json_string = json_encode($json);
?>
<script>
var json_string= '<? echo $json_string; ?>';
var json_object = JSON.parse(json_string); //Fail in this line
</script>
Fail with error message "String literal not ended".
Thanks
Leave the quotes out and it should work:
var json_string = <?php echo $json_string; ?>;
The string returned by json_encode already is a valid JavaScript expression and thus doesn’t need any further declarations.