fartagaintuxedo fartagaintuxedo - 4 months ago 10
PHP Question

Best place in html page for php block when passing variables to javascript

I have a simple HTML page and I feel unsure about which is the best place to put a PHP block that loads 2 JSON arrays from files so that they can then be passed on to JavaScript variables.

I have placed it here, but I have no criteria:

<!DOCTYPE html>

//i have placed the block here
<?php
$twit_collection=file_get_contents('cdtwbot_twit_collection.json');
$tag_collection=file_get_contents('cdtwbot_tag_collection.json');
?>

<html>
<head>
<script type="text/javascript">
//pass PHP variables declared above to JavaScript variables
var twit_collection = <?php echo $twit_collection; ?>;
var tag_collection = <?php echo $tag_collection; ?>;
</script>
</head>

<body>
//document continues...
</body>
</html>


Would it be better placed inside the
<head>
tag? Or somewhere else?

There is a great post about passing variables from PHP to JavaScript here but it doesn't cover this point.

Answer

From a purely technical standpoint, I'd say it doesn't matter. You can put your php code anywhere on the page, so your solution makes as much sense as putting it anywhere else. There are no convention where to put php code, such convention like you should put your JS code in the <head>, but if you want one I'd say insert it next to the JavaScript variables, because it makes the code more understandable.

In this very example, however I wouldn't use separate variables for this case, as it just confuses the matters, and slows down the code. (Unless, of course, you want to use the variables more than once.)

I'd change the code to this:

<script type="text/javascript">
     var twit_collection =
          <?php echo file_get_contents('cdtwbot_twit_collection.json'); ?>;
     var tag_collection =
          <?php echo file_get_contents('cdtwbot_tag_collection.json'); ?>;
</script>

Also, I'd add that this is needless to use php in this case, as JavaScript can parse JSON files much faster than PHP, and it makes much more sense not to mix these two types of code. I'd rather just make these variables in the JSON file ( var twit_collection = ... ) and include it into my html as I can. Look at this article here, the 49 upvoted answer (second answer) pretty much clarifies my point.