Welcome Guest, Not a member yet? Register   Sign In
CI constant in JS script
#1

[eluser]obiron2[/eluser]
I'm making increasing use of Ajax and would like to maintain use of full URIs in Ajax calls. What is the best way of setting base_url() and site_url() in JS.

FYI all of my JS is in a separate script file and so is not dynamic.

If I sent a small script as part of the main page header

Code:
print "#script# var BaseURL = ".base_url().";";
print  "var SiteURL = ".site_url()."; #/script#";

would this then be available to the JS file as a global variable, or is there a more elegant solution.

Obiron
#2

[eluser]xenon-dev[/eluser]
As long as the JS file is external, you can't do any server-side thingies in it. However, you could create some macros, and parse the JS file into a php variable, then replacing the macros. It would look like this (roughly):

the JS file:
Code:
<#BASE_DIR#>

and in PHP you would have:
Code:
$js = file_get_contents( 'file.js' );

$js = str_replace( '<#BASE_URL#>', 'your base url', $js );

After making the replacements, you will have to either output the JS as part of the current page (in a script block) and removing the script src from your page (so the functions, vars, etc, will not be defined again), or overwrite the existing JS file, while keeping the script src tag.

I can't see a more elegant solution, so I hope this will help you. Cheers!
#3

[eluser]marcoss[/eluser]
Code:
&lt;script type="text/javascript"&gt;
    var php_var = "&lt;?=$php_var?&gt;";
&lt;/script&gt;
&lt;script type="text/javascript" src="&lt;?=HOME?&gt;/js/jquery.js">&lt;/script&gt;




Theme © iAndrew 2016 - Forum software by © MyBB