9

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

18
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

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

  • this is better because sometime the JS version bugs – CompactCode Jul 17 '18 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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