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

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
$config['allow_get_array']= TRUE;

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:
$data = array('name' => $userid);
$this->load->view('fb', $data);

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

in the JS file:
<?php header('Content-type: text/javascript');?>
$(document).ready(function() { //start document ready
}); //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.

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.

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

var foo = <?php echo $foo; ?>;

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

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