I am using Codeigniter and want to separate the JavaScript from the view files, but many of the JavaScript functions need data from controller (it depended on values from controllers)
ex:
controller :
function show_post() {
$data['data'] = $this -> get_data(); //some data
$data['random_key'] = $this -> generate_random(); //returns a random value
$this -> load -> view('posts', $data);
}
and in view I have a js function:
<script>
function get_random() {
return "<?= $random_key; ?>";
}
</script>
How can I save this javascript snippets to some other file say posts.js? If I did something like this then I cannot use php variables inside the script.
What is the best way to achieve this in terms of Performance and Maintenance?
Some other ways I do not want to follow :
- Save the JS file as a PHP file and then pass the values to that file
- Declare all those variable in the view file globally