Hardcoding codeigniter’s base_url into your javascript file

Its so easy and straight forward with hard coding base_url into our scripts but as your project grows and as you upload your projects into the production server then edit it is a bit frustrating. There must be a better way to handle these base_url automatically into our js files.

Well, there is, no, actually there are a handful of methods:

we could use HTML5 and add our base url path as part of the body attribute like this:

<body data-baseurl="<?php echo base_url(); ?>">

then we refer our baseurl in javascript as

var baseurl = $('body').data('baseurl');
alert(baseurl+"login/check");

Or use base tag to set our default url for all relative paths like this:

<head>
  <base href="<?php echo base_url(); ?>">
</head>

Another way is to use environment variables to store our base url in Javascript

var codeigniter = {
  baseurl: <?php echo base_url(); ?>
}

then we refer our baseurl in javascript as

alert(codeigniter.baseurl+"login/check");

Which one do you use?

1 Comment
  1. buddy you solve my problem

Leave a Reply