Welcome Guest, Not a member yet? Register   Sign In
Passing variable to external javascript file in uri
#1

[eluser]Bramme[/eluser]
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
Code:
$this->template->add_js('assets/js/file.js?baseurl='.base_url());

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
#2

[eluser]TheFuzzy0ne[/eluser]
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;';
</script>

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

[eluser]Bramme[/eluser]
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.
#4

[eluser]TheFuzzy0ne[/eluser]
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.

Code:
class Get_js extends Controller
{

    function Get_js()
    {
        parent::Controller();
    }

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




Theme © iAndrew 2016 - Forum software by © MyBB