I have such a js script:
$(".order-event-btn").click(function(e) { $.ajax({ url: "URL", type: "POST", data: { eventId: $(e.target).attr('data-event-id'), }, success: function(data) { //Some code }, error: function(data) { //Some code }, }); }); I connect the script through the asset bundle "BookAsset".
In this area:
url: "URL", I need to pass the URL to action "book-event" (book an event) in the controller Book (booking, not a book :)).
On the server, I can do this:
Url::to('/book/book-event') But how do I get the URL on the client?
There is such an option:
- The script is connected via BookAsset.
In view I register
\ frontend \ assets \ BookAsset :: register ($ this);
In view I write the same way and I have the variable bookEventURL available to the js file.
$ this-> registerJs ('var bookEventURL ='. Url :: to ('/ book book book-event'). ';');
But I do not like this decision. What will happen when I use this script not in one view? Do I constantly have to declare the variable bookEventURL?
Question Is it possible to somehow bind js-variables to the Asset bundle (my BookAsset). That is, when I register my BookAsset, automatically something like this is inserted into the source code of the page:
<script>var bookEventURL = "http://example.com/book-event/";</script>
$this->registerJsFile('/js/file.js', ['position'=>yii\web\View::POS_END]);- MasterAlex