How to Pass Config Information to JS? |
[eluser]CodeIgniterNewbie[/eluser]
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.
[eluser]Buso[/eluser]
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
[eluser]slowgary[/eluser]
Remember also, your browser doesn't necessarily care what your file extensions are. So you could potentially do something like this in your pages: Code: // point your script to a CodeIgniter Controller Code: class Myjavascript extends Controller Code: 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
[eluser]_krc_[/eluser]
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
[eluser]slowgary[/eluser]
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
[eluser]slowgary[/eluser]
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.
[eluser]Twisted1919[/eluser]
The best solution i found is to have somewhere in your <head> of the website someting like: Code: var site = { Code: site.base_url ; |
Welcome Guest, Not a member yet? Register Sign In |