//ads:
?>
Passing PHP JSON to Javascript: echo json_encode vs echo json declaration
PHP Snippet 1:
<?php
$array = array("const1" => "val", "const2" => "val2");
?>
<script>
var contants = <?php echo json_encode($array); ?>
</script>
PHP Snippet 2:
$array["<key>"]
PHP Snippet 3:
contants.const1, ....
PHP Snippet 4:
// holds variables from PHP
var stuff = {};
try {
// stuff will always be an object
stuff = JSON.parse('<?php echo empty($stuff) ? '{}' : json_encode($stuff) ?>');
} catch (e) {
if (e instanceof SyntaxError)
{
// report syntax error
console.error("Cannot parse JSON", e);
}
}
// show resulting object in console
console.log("stuff:", stuff);
PHP Snippet 5:
$array = array("const1" => "val", "const2" => "val2");
echo json_encode($array);
PHP Snippet 6:
"{\"const1\": \"val\", \"const2\": \"val2\"}"
PHP Snippet 7:
$json_array = array(
"const1" => "val",
"const2" => "val2"
);
$json_obj = json_encode($json_array);
PHP Snippet 8:
var locations = <?php echo json_encode($sample_location_master); ?>;