What Is The Best Practice To Pass The Controllers' Url To The Js?


What is the best practice to pass the controllers’ url to the javascript code? For example for an ajax.

I used this case:

<script type="text/javascript">



                type: "POST",

                url: '<?php echo 'http://localhost/' . \yii\helpers\Html::url(['betting/index']); ?>',

                data: { day: "kedd"}

             }).done(function( data ) {





Are there any Yii functions to get the Host Url? Of course I can use the basic PHP, but I think it will more better if the only


can pass the Host url too, or not?


's documentations says to me I can use empty string as paramater, and this will return with the currently requested URL, and this is very good :).

But why not without parameter? Why do I have to use empty string?

Works for me.


I wonder if there’s a shortcut for this.

I have no idea either.

Ah yes, however I don’t understand why it is not under the Helper in the Html class.

For me it will be more logical… But this is only my opinion. (I searched for this in the Html class)

Thanks for the help :):

Yes createAbsoluteUrl is the best method.

For specific cases you can also store Yii::$app->urlManager->baseUrl in a variable $baseUrl and concat this to your Html::url or createUrl functions to get a kind of absolute url.

I use this in my main template because I need it in my .js files (which don’t have access to php):


<script>var baseUrl = "<?= Html::url(["/"]); ?>";</script>


(Note the "/" inside of an array - this is important)

Then I can just use:


                type: "POST",

                dataType: "json",

                url: baseUrl + "controller/action",

                data: {

                    id: id


            }).done(function (data) {

                // process