Magento – Magento 2 get admin base url in custom js

base-url

I have added custom js to create module for a functionality.
I need to call ajax in my custom js but I need Base url of admin in js file.
How I will get this?
I tried

function createBooking(){
    orderId =4;
if(orderId ==null){
    alert('Order id does not found')
    }else{
 require(['jquery'], function ($) {
                   $.ajax({
            url: {Here I need admin base url},
            type: 'POST',
            data: {isAjax: 'true', form_key: FORM_KEY,order_id:orderId}
        });
    });
             }    //else 
} // createBooking

Best Answer

You can pass url for ajax request as argument when initializing your component.

view.phtml

<div data-mage-init='{"Vendor_Name/js/you/component": {"url": "<?php echo $block->getUrl('your/route'); ?>"}}'>

component.js

define([
    'jquery'
], function ($) {
    'use strict';

    return function (config, element) {
        $(element).click(function () {
            console.log(config.url)
        });
    };
});
Related Topic