Javascript + base_url()


Here's my doubt.

i have a javascript file (global.js) that loads into view. (script src="....")

so far so good. but inside that js file, i have a Ajax.Updater calling.

new Ajax.Updater('/subdir/controller/method/args', 'my_div', {});

What I want is put a base_url in '/subdir/', cause probably the subdir of application will change (i don't know what will be the name, so i need to use base_url).

If the js was wrote in the view, it's ok, i could use
new Ajax.Updater('<?=base_url();?>controller/method.....

But that's not the case :blank:

Helps? Ideas? Lights?


ignore this I found a better solution (see below)

Oh hang on I got it!!

  var base="<?=base_url();?>";
<script src="<?=$base_url();?>js/myjavascript.js"></script>

Then base will be a variable available in the javascript.

I dug out some old code so I know it works..
  var image = base + "img/welcome.png"

[eluser]Derek Allard[/eluser]
You are welcome to see how I did it in BambooInvoice and also in if that's helpful.

can i do this in css too?

background-image: url(something like that joe/image.png);

i'll see that js after lunch :-P


[eluser]Derek Allard[/eluser]
You can't use base_url in CSS, because the PHP won't get parsed, but you can just say
background-image: url(/something_like_that_joe/image.png);

Notice the "/" at the beginning? It means "start from the web root". There lots of info on the forum if you poke around for it.

OK Derek, that i knowed.

My fck problem is that the application maybe move someday to a subdir. If this happen, i'm fc$%*, cause it's a very big application. And i don't wanna change all views/css/javascript.

That solution about base in javascript works fine (thanks gtech).

Today my app is working very well. The css has "/" in the background-image element.

In fact, i only ask to see if someone has a better solution than mine. It's not a problem today.


As far as the CSS goes, I keep stylesheets and their related images in the same directory so I can reference the images relatively as "background: url(image.gif) ...". Then I use base_url in my html to include the stylesheet as usual. I move sites to different locations/directories all the time with no problem.

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

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