Include PHP inside JavaScript (.js) files

7 years later update: This is terrible advice. Please don’t do this.

If you just need to pass variables from PHP to the javascript, you can have a tag in the php/html file using the javascript to begin with.

<script type="text/javascript">
    var phpVars = <?php echo json_encode($vars) ?>;
</script>
<script type="text/javascript" src="yourScriptThatUsesPHPVars.js"></script>

If you’re trying to call functions, then you can do this like this

<script type="text/javascript" src="YourFunctions.js"></script>
<script type="text/javascript">
    // assume each element of $arrayWithVars has already been json_encoded
    functionOne(<?php echo implode(', ', $arrayWithVars); ?>);

    functionTwo(<?php echo json_encode($moreVars) ?>, <?php echo json_encode($evenMoreVars) ?>);
</script>

Leave a Comment