PHP Var to External JS — Without Global, Ajax, or Eval

amarneZes

New Member
How can I access a JSON array from a PHP variable in an external JavaScript file without creating a global variable?I have a PHP variable $customers that contains a json_encoded array:\[code\]$customers = [{"id":"12","name":"Abe Adams"},{"id":"17","name":"Bill Brown"}]\[/code\]I want to use the contents of the array in a jQuery UI Autocomplete text input.Rather than make an Ajax request for the autocomplete options, I'd prefer to use the values in the $customers array, which is passed in and ready to go when the user arrives at the page.I know I can pass the contents of $customers to a JavaScript variable prior to loading the external JavaScript file:\[code\]<script>var customers = <?php echo $customers; ?></script><script src="http://stackoverflow.com/questions/10860043/external.js"></script>\[/code\]But this requires creating a global JavaScript variable.Is there a better way to access the $customers array from my external JS file?This question has been asked several times previously:Question: Access PHP var from external javascript file Accepted Answer: Create global varQuestion: Pass vars from php to js without ajax Top Answer: Use AjaxQuestion: php file send variable to .js external file Top Answer: Use AjaxQuestion: Reading a PHP file variables from external JSTop Answer: Use evalQuestion: Return JSON data from PHP, and use it using JavascriptAccepted Answer: Create global var
 
Top