Get base url from js file
-
10-05-2021 - |
Question
i want to retrieve a base url and append it with my module controller link from .js file, so it's impossible to use block to get the base url. so far i've done this:
define([
'jquery',
'mage/url'
], function ($,url) {
var linkUrl = url.build('namespace_module/regions/index');
console.log(linkUrl);
});
but i only got this result:
namespace_module/regions/index
Solution
define([
'jquery',
'mage/url'
], function ($,url) {
var linkUrl = url.build('frontname/regions/index');
console.log(linkUrl);
});
Where frontname is your routes.xml file frontname.
You have to pass your frontname from routes.xml file instead of module name(namespace_module)
You can lookup your routes.xml file from app/code/Namespace/Module/etc/frontend/routes.xml
OTHER TIPS
You can retrieve the baseUrl from the global js variable BASE_URL, and use it by setting the baseUrl from the mage/url module.
define([
'jquery',
'mage/url'
], function ($, url) {
url.setBaseUrl(BASE_URL);
var link = url.build('foo/bar');
console.log(link); // https://magento.com/foo/bar
});
this will return the absolute url.
I'am not sure what you are doing but i think you should pass url to js(widget).
Url is parameter of js widget
Put script below to your template where you want
<script type="text/x-magento-init">
{
"*": {
"Magento_Ui/js/core/app": {
"components": {
"yourWidget": {
"dataUrl": "<?php echo $block->getBaseUrl(); ?>"
}
}
}
}
}
</script>
In javascript widget you can access to dataUrl
define(['uiComponent'], function(Component) {
'use strict';
return Component.extend({
initialize: function() {
console.log(this.dataUrl);
}
});
});
Another approach
<script>
window.testUrl = <?php echo json_encode($block->getBaseUrl()); ?>
</script>
In your custom js you can easy access to window.testUrl global variable
Add this code in phtml file :
<input type="hidden" value="<?php echo $this->getUrl(); ?>" id="baseUrl"/>
Now you can use this base url in js file by id :
$("#baseUrl").val();
This may be useful. I also check it and it is working.