Welcome Guest, Not a member yet? Register   Sign In
URL in Javascript best practice
#1

[eluser]codeboy[/eluser]
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.
Code:
var locationhost = location.host;
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 example.com

http://example.com/www/cd_cntrlpanel/getLessonsForLevel

Thanks,
CB
#2

[eluser]Pascal Kriete[/eluser]
Create a variable from php that sets your base path:
Code:
// 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";

?>
};
//-->
</script>

// .... 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 ]
#3

[eluser]codeboy[/eluser]
Thanks ip. This should work for me.




Theme © iAndrew 2016 - Forum software by © MyBB