4

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
konika
  • 579
  • 2
  • 7
  • 23

1 Answers1

3

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)
        });
    };
});
Max
  • 4,054
  • 17
  • 22
  • Hi max thanks for reply , but I am not using any phtml file I have added link by script in core phtml file. And after click on it I have called this function in my custom js. so how I add it? – konika Dec 26 '16 at 09:33
  • you can use variable $block in any phtml file. If you need to use url in inline js, located in .phtml file, you can output url in js variable. Example: $.ajax({url: "getUrl('your/route'); ?>"}); – Max Dec 26 '16 at 11:29
  • you need to initialize your script from outputted phtml file. – Max Dec 26 '16 at 11:32