Welcome Guest, Not a member yet? Register   Sign In
Need help passing a variable to an external javascript file embedded in a view
#1

[eluser]chamilyan[/eluser]
I am loading a view from a controller with a data array. I need to pass a variable from the data array to a javascript file called by my view page. I can reference the .JS file however the context does not allow me to send any of the data variables to it. How can I do this easily without tooo much more hacking? I don't want to use query strings but I have
Code:
$config['allow_get_array']= TRUE;
enabled.

Here is what I'm currently doing to refer to the javascript (jQuery) file in my view. As you can see I'm attempting to append a hash and refer to my variable that way, but this isn't working. I'm pretty sure there is an easier, less hacky way to do this anyways.

in the controller:
Code:
$data = array('name' => $userid);
$this->load->view('fb', $data);

in the view:
Code:
[removed][removed]
<?php $JSurl = site_url('../JS/js.php').'#'.$name;?>
[removed][removed]

in the JS file:
Code:
<?php header('Content-type: text/javascript');?>
$(document).ready(function() { //start document ready
alert(this.hash);
}); //end document ready

I'm echoing the Jquery library on the top part and $JSurl within J-SCRIPT tags in the [removed] code portions, not sure why they wouldn't post.
#2

[eluser]chamilyan[/eluser]
well, got this to work as long as the javascript is in the loaded view context, but still dont know how to refer to the variable in the external JS file outside of the codeigniter application folder.
#3

[eluser]byde[/eluser]
Actually i think you will have cache problems with JS files.
If the JS file is static and the only dinamic part are variable you can start them at the view

Code:
[removed]
var foo = <?php echo $foo; ?>;
[removed]
[removed][removed]

the order can be different depending on what you need to do
#4

[eluser]Aken[/eluser]
An alternative you could consider is to add the variable needed by the Javascript to some sort of HTML element in your view, and then use JS to pull that variable and then do whatever you need with it.




Theme © iAndrew 2016 - Forum software by © MyBB