CodeIgniter Forums

Full Version: URL in Javascript best practice
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

Hey all,
This should be an easy question. I am using YUI with CodeIgniter. I would like to know the best practice for plugging in server URL's in AJAX code such as the following.

This is what I have now and this seems to work. Since this is entirely within JavaScript I d'ont have access to the CI URL helper functions.
var locationhost =;
this.myDataSource = new YAHOO.util.DataSource("http://" + locationhost + "/cd_cntrlpanel/getLessonsForLevel");

If I ignore the locationhost and plugin just the URI segments (as I would like to do), the URI segments seem to get suffixed to after the www folder and I get a 404 (as I should) because that is not where my .php files reside.

this.myDataSource = new YAHOO.util.DataSource("/cd_cntrlpanel/getLessonsForLevel");[/code]

The above results in a page not found error with the following URL being generated (notice the www after the


El Forum

[eluser]Pascal Kriete[/eluser]
Create a variable from php that sets your base path:
// In the 'header' / 'template' / whatever view:
<script type="text/javascript">
var APP = {
<?php foreach($js_vars as $js_key => $js_value)
echo "'{$js_key}': '{$js_value}',\n";
echo "'site_url': '".site_url()."'\n";


// .... in the javascript file

var l_req = $C.asyncRequest('GET', APP.site_url + 'login', l_callback);

[EDIT: A little too liberal on the copy-paste there. The 'site_url' is the important part Wink ]

El Forum

Thanks ip. This should work for me.