:::: MENU ::::
Posts tagged with: M2 get base url

Magento 2 Get base url in js

This tutorial is about magento 2 Get base url in js file. First of all i assume that you are familiar with magento 2 and hence you are at this level where you want to know how to get base url from js file in magento 2. Above all if you are not familiar with advance magento concepts and are looking for basics,please look for magento 2 basic tutorials.

So lets start our tutorial and focus on our topic. For example if you want to get base url from .js file and append it with your module controller link from. How can we do it? It is almost impossible to use block to get the base url.

Get base url

So we will look at the way how we can get base url. to do that,paste the following code in your routes.xml file

define([

   'mage/url'
], function (url) {

  var linkUrl = url.build('test/test/test');
  console.log(linkUrl);
});

Where frontname is your routes.xml file frontname.

Since it is necessary,you have to pass your frontname from routes.xml file instead of module name(namespace_module).

Furthermore you can lookup your routes.xml file from

app/code/QaisarSatti/HelloWorld/etc/frontend/routes.xml

It might work for some and might not for others.

Further more Add this code in phtml file:

<input type="hidden" value="<?php echo $this->getUrl(); ?>" id="baseUrl"/>

having done that you can use this base url in js file by id :

$("#baseUrl").val();

It is a quite useful and tested trick. So i thought to share it.

There is another approach for this task.Having said that it may too be useful.

You should pass url to js(widget).Url is a parameter of js widget.And put script below to your template where you want to.

<script type="text/x-magento-init">
{
    "*": {
        "Magento_Ui/js/core/app": {
            "components": {
                "yourWidget": {
                    "dataUrl": "<?php echo $block->getBaseUrl(); ?>"
                }
            }
        }
    }
}
</script>

Similarly in javascript widget, you can access to dataUrl by below code.

define(['uiComponent'], function(Component) {
    'use strict';

    return Component.extend({
        initialize: function() {
            console.log(this.dataUrl);
        }
    });
});

Another simple approach is

<script>
window.testUrl = <?php echo json_encode($block->getBaseUrl()); ?>
</script>

Using your custom js you can have easy access to window.testUrl global variable.

That’s it from this tutorial. I hope it serves the purpose.

Since these tutorials are for learning purpose please feel free to drop any suggestions or queries in comments section. That will definitely be highly appreciated.

Author: Qaisar Satti
Category: Magento 2
Last Modified: October 12, 2018