77

I am building a website with CodeIgniter, I have various resources that I load with the base_url helper function like this

<link rel="stylesheet" type="text/css" href="'.base_url('assets/css/themes/default.css').'" id="style_color"/>

which produces (i.e. www.mysite.com)

<link rel="stylesheet" type="text/css" href="http://www.mysite.com/assets/css/themes/default.css" id="style_color"/>

I can then swap this resource with another in javascript like this

$('#style_color').attr("href", "assets/css/themes/" + color_ + ".css");

what happens is that it will try to load the resource without using the absolute path generated by php, so my solution was adding a dummy tag in every page with php like this

<div id="base_url" class="'.base_url().'"></div>

I then modified the javascript line to

$('#style_color').attr("href", $('#base_url').attr("class") + "assets/css/themes/" + color_ + ".css");

it does work but it doesn't look elegant at all, so, I would appreciate any help on how to maybe generate this base url from within javascript or any other solution, thanks :)


I preferred a Javascript only solution and since I am using CodeIgniter, a document.base_url variable with the segments of the url from the protocol to the index.php seemed handy

document.base_url = base_url('index.php');

with the function base_url() being

function base_url(segment){
   // get the segments
   pathArray = window.location.pathname.split( '/' );
   // find where the segment is located
   indexOfSegment = pathArray.indexOf(segment);
   // make base_url be the origin plus the path to the segment
   return window.location.origin + pathArray.slice(0,indexOfSegment).join('/') + '/';
}
Nehemias Herrera
  • 1,751
  • 1
  • 14
  • 12
  • I am using the same thing but I am using hidden readonly field to store base_url() as I was facing some problem passing it in class name. – Dirgh Jan 21 '14 at 00:24
  • I dont get why you add a class with a `base_url`, you can read this to see how to get the base_url in js http://stackoverflow.com/questions/1420881/javascript-jquery-method-to-find-base-url-from-a-string/11775016#11775016 – Emilio Gort Jan 21 '14 at 00:24

11 Answers11

221

Base URL in JavaScript

You can access the current url quite easily in JavaScript with window.location

You have access to the segments of that URL via this locations object. For example:

// This article:
// https://stackoverflow.com/questions/21246818/how-to-get-the-base-url-in-javascript

var base_url = window.location.origin;
// "http://stackoverflow.com"

var host = window.location.host;
// stackoverflow.com

var pathArray = window.location.pathname.split( '/' );
// ["", "questions", "21246818", "how-to-get-the-base-url-in-javascript"]

In Chrome Dev Tools, you can simply enter window.location in your console and it will return all of the available properties.


Further reading is available on this Stack Overflow thread

Community
  • 1
  • 1
chantastic
  • 10,519
  • 4
  • 25
  • 20
  • I am not convinced about this answer being right. base_url is defined in php (server side), how do you get in JS/client side? – PC. Oct 12 '19 at 09:27
  • 2
    @PC. `base_url` (in this example) is just the name of my variable. it could be `baseURL`, `urlBase`, or anything. – chantastic Oct 15 '19 at 20:55
9

One way is to use a script tag to import the variables you want to your views:

<script type="text/javascript">
window.base_url = <?php echo json_encode(base_url()); ?>;
</script>

Here, I wrapped the base_url with json_encode so that it'll automatically escape any characters to valid Javascript. I put base_url to the global Window so you can use it anywhere just by calling base_url, but make sure to put the script tag above any Javascript that calls it. With your given example:

...
$('#style_color').attr("href", base_url + "assets/css/themes/" + color_ + ".css");
sean
  • 877
  • 10
  • 16
6

Base URL in JavaScript

Here is simple function for your project to get base URL in JavaScript.

// base url
function base_url() {
    var pathparts = location.pathname.split('/');
    if (location.host == 'localhost') {
        var url = location.origin+'/'+pathparts[1].trim('/')+'/'; // http://localhost/myproject/
    }else{
        var url = location.origin; // http://stackoverflow.com
    }
    return url;
}
hsn0331
  • 372
  • 8
  • 21
5

This is done simply by doing this variable.

var base_url = '<?php echo base_url();?>'

This will have base url now. And now make a javascript function that will use this variable

function base_url(string){
    return base_url + string;
}

And now this will always use the correct path.

var path    =   "assets/css/themes/" + color_ + ".css"
$('#style_color').attr("href", base_url(path) );
Muhammad Raheel
  • 19,823
  • 7
  • 67
  • 103
5
var baseTags = document.getElementsByTagName("base");
var basePath = baseTags.length ? 
    baseTags[ 0 ].href.substr( location.origin.length, 999 ) : 
    "";
goofballLogic
  • 37,883
  • 8
  • 44
  • 62
4

To get exactly the same thing as base_url of codeigniter, you can do:

var base_url = window.location.origin + '/' + window.location.pathname.split ('/') [1] + '/';

this will be more useful if you work on pure Javascript file.

Sandeep Sukhija
  • 1,156
  • 16
  • 30
Saddam
  • 41
  • 3
3

You can make PHP and JavaScript work together by generating the following line in each page template:

<script>
document.mybaseurl='<?php echo base_url('assets/css/themes/default.css');?>';
</script>

Then you can refer to document.mybaseurl anywhere in your JavaScript. This saves you some debugging and complexity because this variable is always consistent with the PHP calculation.

Schien
  • 3,855
  • 1
  • 16
  • 29
  • What about browser compatibility with this? Is it possible that some browsers (or older ones) this could fail? – Alejandro Apr 17 '15 at 16:33
  • this should be cross browser because the differences are eliminated by a server-side script. this code may not be "portable", meaning that you might have to adjust the path prefix when you move the server. – Schien Apr 19 '15 at 15:04
1

Should you want what is exactly specified in the web page, just use:

document.querySelector('head base')['href']
Jérôme Beau
  • 10,608
  • 5
  • 48
  • 52
0

in resources/views/layouts/app.blade.php file

<script type="text/javascript">
    var baseUrl = '<?=url('');?>';
</script>
Pasindu Jayanath
  • 892
  • 10
  • 27
0

Let's say you have your global scripts file and you don't want to define that URL repeatedly in other files. That's the point where BASE_URL kicks in.

In your global_script.js file, do this

<script>
 var BASE_URL = "http://localhost:8000";
</script>

Then you can use that variable anywhere else to call your URL. For example...

<script>
   fetch(`{{BASE_URL}}/task-create/`,{
         ..............
            
        }).then((response) => {
            .............
   })
</script>
Shedrack
  • 656
  • 7
  • 22
-1

I may be late but for all the Future geeks. Firstly i suppose you want to call base_url in your .js file. so lets consider you are calling it on below sample .js file

sample.js

var str = $(this).serialize(); 

jQuery.ajax({
type: "POST",
url: base_url + "index.php/sample_controller",
dataType: 'json',
data: str,
success: function(result) {
alert("Success");
}

In the above there is no base_url assigned.Therefore the code wont be working properly. But it is for sure that you'll be calling the .js in between <head></head> or <body></body>of View file by using <script> </script> tag. So to call base_url in.js file, we have to write the below code where you plan to call the .js file. And it is recommended that you create common header file and place the below code and all the calling style sheets (.css) and javascript (.js) file there. just like below example.

common header file

<head>

<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/js/sample.js">

<script>
  var base_url = '<?php echo base_url(); ?>';  
</script>


</head>

Now the base_url will work in sample.js file as well. Hope it helped.

Jeeva
  • 632
  • 1
  • 12
  • 21