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

1 Answer 1

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)
        });
    };
});
3
  • 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? Commented Dec 26, 2016 at 9: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: "<?php echo $block->getUrl('your/route'); ?>"}); Commented Dec 26, 2016 at 11:29
  • you need to initialize your script from outputted phtml file. Commented Dec 26, 2016 at 11:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.