0

I have try to get base url using mage/url in my custom js , but it return url without base url so, is there any another way using that we can get magento base url in js which is added in admin side ?

  • 1
    You can get by pass url from phtml file and get into js file. – Rohan Hapani Feb 27 at 10:07
  • thanks @Rohan , this is the one way we can do and working great !!! – Sanjay Shiyal Feb 27 at 11:56
  • is there any another way that we can get solution with single js file without using phtml? – Sanjay Shiyal Feb 27 at 11:56
2

mage/url widget is not used to fetch backend base URL in Magento 2.

You need to create a template file using layout XML and define the base URL of backend under the template file.

You can define any Global variable and set your URL in it.

Create a simple layout XML file to fetch backend URL of the site using JS,

Create default.xml file for global access at admin area or create a specific action layout file for a specific page,

File Path:  app/code/VendorName/MyModule/view/adminhtml/layout/default.xml

Code Content:

 <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left"
          xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceContainer name="js">
                <block class="Magento\Backend\Block\Template" template="VendorName_MyModule::js.phtml"
                       name="custom_js_backend"/>
            </referenceContainer>
        </body>
    </page>

Now Create js.phtml file,

File Path: app/code/VendorName/MyModule/view/adminhtml/templates/js.phtml

Code Content:

<script>
        require([
            "prototype"
        ], function () {
            window.customUrl = "<?= /** @noEscape */ $block->getUrl('frontname/index/index')?>";
            var customUrl = window.customUrl;
        });
    </script>
1

In phtml file add this code:

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

By using Id we can get base url in JS file

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

Hope it will help

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.