• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Passing variable to external javascript file in uri

Hey all

I'm messing around with javascript in a project (still learning a lot, i don't know much javascript). I'm putting all the js I have in an external file, to keep my page somewhat clean, but I've encountered an issue:

I would like to pass the base_url() to one of the external js files. Now I thought I once saw a js library use smth like "file.js?foo=bar", since I'm using the template library, I could very easily use

I've googled this but didn't find anything that could really help me. Using baseurl in my file.js doesn't work either, that would've been too easy I guess :p

Why not keep the file untouched, and just add something to the page itself, like this to your view:

<script type="text/javascript">
var base_url = '&lt;?php echo base_url(); ?&gt;';

You'd probably need to print that before you load the external script, however.

yeah okay, i could do that, but that means adding extra script tags. I was hoping to be able to do it without those and I'm really just wondering if it's possible at all.

It probably is possible, but I think it makes things too complicated. You could probably get the PHP parser to parse JavaScript files on request, and you could then take the arguments from the URI, and insert them into the JavaScript file, but that's extra server work for the sake of saving a line of HTML code.

Another idea might be to have your JavaScript grab the data from a cookie, but again, it just over-complicates things.

Oh and one more idea, which might not be quite so complicated, but does mess up your structure slightly, might be to have a controller method that returns the specified JavaScript file after it's been parsed. That way, you only need to request JavaScript files that need parsing via the controller, all other files come straight from your js subdirectory in your Web root.

class Get_js extends Controller

    function Get_js()

    function file($file_name="")
        # Grab parameters from URI, or session..
        # include the javascript file (but buffer the output).
        # Send the headers and file contents.

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.