Reputation: 6378
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 :
Upvotes: 0
Views: 142
Reputation: 1339
the simplest method is that , define php variables as js variable in your view file
<script type="text/javascript">
var random_key = <?= $random_key; ?>;
</script>
then you can use that variable in your example.js
file
Upvotes: -1
Reputation: 3289
One way to do it by using hidden fields, in your case store them in hidden field like:
<input type="hidden" value="<?php echo $random_key;?>" id="randomkey">
and access them in js by using ID like:
$("#randomkey").val();
In this way you can use controller paramter in your js.
Help it will help you!
Upvotes: 1
Reputation: 100175
you could pass the value as parameter to your js function, like post.js
function get_random( param ) {
//use param here
}
//OR
function get_random( ) {
//get arguments like
var firstArg = arguments[0];
}
view.php
//include post.js file
//call the js function passing php variable as parameter, like
get_random("<?php echo $random_key; ?>");
did you mean something like this
Upvotes: 1