I\'m trying to create a common constants file to share between php and javascript, using JSON to store the constants. But I\'m wondering why pass the JSON from PHP to javasc
It all depends on what you want to send from server to the client - be it a data (JSON) or some code.
Two approaches:
Echo a JSON file on a server - then you print your JSON document and set response Content-Type
to application/json
. This way you can use any AJAX library you wish, like $.get
or raw XMLHttpRequest
etc. It is a way of passing data.
Echo a Javascript code on a server and then use $.getScript
to load it. It's a way of passing code. This is potentially less secure, because your code can contain not only JSON, but also any arbitary code. So if attacker can compromise your server, he could be able to push code to any client for a remote execution.
If you want to pass data only, go with first approach. It's cleaner and more safe.
Additionally, if you ever end up writing frontend in different environment, say different programming language, you'll be able to resuse the same JSON-returning endpoint. It'll be harder if you return Javascript code.
constant.php
<?php
$array = array("const1" => "val", "const2" => "val2");
?>
<script>
var contants = <?php echo json_encode($array); ?>
</script>
======================END OF FILE constant.php=======
In php you can access using
$array["<key>"]
In javascript, you can access using
contants.const1, ....
You use json_encode
if you use php array not a string:
$array = array("const1" => "val", "const2" => "val2");
echo json_encode($array);
if you call json_encode on a string you will get:
"{\"const1\": \"val\", \"const2\": \"val2\"}"