Welcome Guest, Not a member yet? Register   Sign In
passing php variables to external .js files
#1

[eluser]neomech[/eluser]
Hi there. I have a feeling this is a simple problem, but I can't figure it out.

I have a site that uses some dynamic javascript in the view. I know how to pass php variables to the view from my controller and use them to create the javascript I want on the page.

What I am trying to do is pass the variables to an external javascript file. I like to keep all my javascript code in external files (and that seems to be widely encouraged). I know how to use a dynamic external .js file using the .php extension, and I can run php code in the external javascript file just fine.

What I DON'T know how to do is to pass php variables from my controller that will somehow make their way into the external javascript files. I realize I could call the external javascript files with a querystring that I could set dynamically, but what if I want to pass in an array, or a simplexml object or something. I tried using global variables and didn't seem to get anywhere with that.

Does anyone know how to do what I'm attempting? Is it even possible?
#2

[eluser]kierownik[/eluser]
I think you can call them the same way as in the view.

If you use
Code:
Controller:
$data['test'] = 'test';

View and java-script:
$test;
It should work I think!
#3

[eluser]layer8[/eluser]
still not work for me,

I have external javascript file(map.js),

From my view(view_home.php), I call function initialize(); function(map.js) that will show all record passed from controller($data('allrecord')Wink.

If the javascript function is in the same file with view_home.php, It'll give no problem with simple call $allrecord, but when initialize() function is moved to map.js, $allrecord is empty.

Please help me,
#4

[eluser]CroNiX[/eluser]
What I do is in the head of my document, which is part of a view file that gets parsed by CI, I define the variables.
Code:
<skript type="text/javascript">
  var base_url = "&lt;?php echo base_url(); ?&gt;";
  //etc
</skript>
Then my external js apps can use base_url because it is already defined in js in the head of the document, before any other scripts are loaded.
#5

[eluser]layer8[/eluser]
whoa,, nice trick, Big Grin thnx,,,




Theme © iAndrew 2016 - Forum software by © MyBB