16

I want to retrieve a base URL and append it with my module controller link from a JS file, so it's impossible to use a 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

1

6 Answers 6

29
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

3
17

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.

1
  • This was actually pretty helpful addition to the accepted answer :) Thanks
    – gabtzi
    Commented Apr 20, 2020 at 12:34
4

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

1
  • this is better because sometime the JS version bugs Commented Jul 17, 2018 at 23:08
3

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.

3

We can also use BASE_URL to get base URL in js.

How it's working

You can see BASE_URL at head on every page

enter image description here

This is defined in require require_js.phtml

vendor/magento/module-backend/view/adminhtml/templates/page/js/require_js.phtml

0

May be you can get base url from window.checkout.baseUrl

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.