phpjavascriptexternal-js

php arrays in external js file


I have this change request to move all my inline javascript to an external file. I tried a simple copy-paste to a new file, but no luck. I'm getting error at the following line: var grp_list = <?php echo json_encode($arr_grp); ?>; and url: "<?php echo $_SERVER['PHP_SELF']; ?>" I have atleast 20 such occurrences. How do I replace these php variables in external javascript?? I checked lot of forums but did not find any solution.

Thanks a lot for your help!!


Solution

  • In short, you can't pass the PHP variables directly to an external JS file without some work in PHP generating the files, then sending custom headers to treat the file as JavaScript (edit: see post by Marcovecchio if this sounds like a likely solution)... a quick solution is to pass the variables inline so they are global, then use them inside your external file. This will allow for the majority of your JavaScript to be in external files, but also allow you to pass your variables from PHP to JS.

    By no means is this the best solution, but it's more than likely the easiest to get working.

    Here's an example:

    <script type="text/javascript">
        var grp_list = <?php echo json_encode($arr_grp); ?>;
        var url = "<?php echo $_SERVER['PHP_SELF']; ?>";
    </script>
    <script type="text/javascript" src="external.js"></script>