In joomla php there I can use $this->baseurl
to get the base path, but I wanted to get the base path in jquery.
The base path may be any of the follo
the easiest way to get base url in jQuery
window.location.origin
I've run into this need on several Joomla project. The simplest way I've found to address is to add a hidden input field to my template:
<input type="hidden" id="baseurl" name="baseurl" value="<?php echo $this->baseurl; ?>" />
When I need the value in JavaScript:
var baseurl = document.getElementById('baseurl').value;
Not as fancy as using pure JavaScript but simple and gets the job done.
Put this in your header, so it will be available whenever you need it.
var base_url = "<?php echo base_url();?>";
You will get http://localhost:81/your-path-file
or http://localhost/your-path-file
.
Here's a short one:
const base = new URL('/', location.href).href;
console.log(base);
I would recommend for everyone to create HTML base tag in development, then assign the href dynamically, so in production whatever host a client uses, it will automacically addapt to it:
<html>
<title>Some page title</titile>
<script type="text/javascript">
var head = document.getElementsByTagName('head')[0];
var base = document.createElement("base");
base.href = window.document.location.origin;
head.appendChild(base);
</script>
</head>
...
So if you are in localhot:8080, you will reach every linked or referenced file from the base, eg: http://localhost:8080/some/path/file.html
If you are in www.example.com, it will be http://www.example.com/some/path/file.html
Also note that, every location you're on, you should not use references like globs in hrefs, eg: Parent location causes http://localhost:8080/
not http://localhost:8080/some/path/
.
Pretent you reference all hyperlinks as full sentenced without the bas url.
I think it will ok for you
var base_url = window.location.origin;
var host = window.location.host;
var pathArray = window.location.pathname.split( '/' );