Welcome Guest, Not a member yet? Register   Sign In
How to Pass Config Information to JS?

How can I make my JS aware of certain configuration settings in CI (e.g. base_url)? Right now, I am having to set this information in CI and JS; it's a potential point of failure. Ideas? Thanks.

for base url you can just use the html tag <base> http://www.w3schools.com/TAGS/tag_base.asp

the other settings I pass them via CI as you said, just add a view that contains js, and set everything there in js vars

Remember also, your browser doesn't necessarily care what your file extensions are. So you could potentially do something like this in your pages:
// point your script to a CodeIgniter Controller
< script type='text/javascript' src='/myjavascript' >< /script >
Then, in that controller:
class Myjavascript extends Controller
     function _remap()
Then in the "myjavascript" view:
var base_url = "<?php echo $base_url; ?>";

As long as the contents of your view are valid JavaScript, your browser will still be happy, and you can set your JavaScript variables using PHP variables, which means they'll always be consistent.

I hope this helps.

[eluser]ahmed hamza[/eluser]
first make a hidden tag in ur view file 'html' like that

<input type='hidden' id='mybase' value='<?php echo $base; ?>' />

second in ur js file u can get the value using the following

var base=document.getElementById('mybase').value;

now u get the CI base config value in ur js file ,
enjoy ur self

I made the trick easily by putting the base_url to global variable (inside script tag) in the beginning of the template view. I can't imagine to make it any easier Wink

I wouldn't recommend storing server side variables in <input> tags, just for retrieval via Javascript. There's extra overhead involved on the client to retrieve that value from the DOM. It's better to just assign a Javascript variable at the top of your document.

[eluser]ahmed hamza[/eluser]
there no overhead & it's usefull when u need tp pass to external js file

I don't want to argue. It takes more resources to include an additional (and useless) DOM element as well as to ask the browser to retrieve the value from that element. After retrieving that value, you still end up at the same place - a Javascript variable with your PHP value. Why not just start at that place?

The DOM is not a good place to store your variables.

The best solution i found is to have somewhere in your <head> of the website someting like:
var site = {
base_url : '<?php echo base_url();?>',
site_url : '<?php echo site_url();?>,
Then, after this object, include the rest of your scripts, and in your scripts, call it like :
site.base_url ;

Theme © iAndrew 2016 - Forum software by © MyBB