[javascript] how to get the base url in javascript

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('/') + '/';
}

This question is related to javascript php html css codeigniter

The answer is


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.


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) );

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.


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

document.querySelector('head base')['href']

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.


var baseTags = document.getElementsByTagName("base");
var basePath = baseTags.length ? 
    baseTags[ 0 ].href.substr( location.origin.length, 999 ) : 
    "";

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;
}

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");

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

<script type="text/javascript">
    var baseUrl = '<?=url('');?>';
</script>

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>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to codeigniter

DataTables: Cannot read property 'length' of undefined How to set time zone in codeigniter? php codeigniter count rows CodeIgniter: 404 Page Not Found on Live Server Only variable references should be returned by reference - Codeigniter How to pass a parameter like title, summary and image in a Facebook sharer URL How to JOIN three tables in Codeigniter how to get the base url in javascript How to get id from URL in codeigniter? How to disable PHP Error reporting in CodeIgniter?