Red
Red

Reputation: 6378

Separate Javascript file from View

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 :

  1. Save the JS file as a PHP file and then pass the values to that file
  2. Declare all those variable in the view file globally

Upvotes: 0

Views: 142

Answers (3)

Jitesh Tukadiya
Jitesh Tukadiya

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

sandip
sandip

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

Sudhir Bastakoti
Sudhir Bastakoti

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

Related Questions