Aditya Sharma
Aditya Sharma

Reputation: 43

How to use config variable in an external JavaScript file

I am using CodeIgniter framework for one of my project. All is going well for me. I have set a config variable in

application/config/config.php

file. How I did that? Have a look below

$config['my_key'] = 'abcdef123';

The issue is when I am trying to use this variable in an external JavaScript file, it is not putting the value there instead of putting all source. The code I used to get the value in JavaScript file is

var mykey = "<?php echo $this->config->item('my_key'); ?>";

but it is not showing the my_key value, but showing

<?php echo $this->config->item('my_key'); ?>

as it is. So how can I achieve the config value in external JavaScript file? I have included the JavaScript file using my controller.

Upvotes: 1

Views: 1652

Answers (1)

Virendra Jadeja
Virendra Jadeja

Reputation: 873

You can define this global variable above external js like describe below so you can achieve your goal.

<head>
     <script type="text/javascript">
          var mykey = "<?php echo $this->config->item('my_key'); ?>";
     </script>
     <script src="path/to/external/js/other.js"></script>
</head>

Now in external js you can use above variable value.

other.js

var key = mykey;

Let me know if it not works.

Upvotes: 4

Related Questions