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:

  1. The script is connected via BookAsset.
  2. In view I register

    \ frontend \ assets \ BookAsset :: register ($ this);

  3. 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> 

3 answers 3

To transfer the variables "from php to js", I wrote a small component into which I can just drop the data, and it will turn it into json and connect it at the end of the page. The decision, I think the rules, because such data is not much. Thus, in the initial method of your asset, you can feed the component the necessary data and not do it in each twist.
I can not share the component, because it is under the first yii. Maybe a little later I will write under the second.

  • Thank. Perhaps this is what you need. I also thought about this option: write a controller that will accept ajax requests and give urls. And in js to wrap the whole thing. Do you think the rules of the decision? I see only 1 drawback: in fact, there will be 2 requests for each ajax request: 1. Getting the url, 2. The useful request itself. - LostDok
  • Not. Making a separate request for urla is crazy. I talked about the same $ this-> registerJs only in a more convenient wrapper. - zabachok
  • As I understand you have a component that you feed the data. And how do you connect them at the end of the page? Through the widget in the layout? The widget receives json data from this component and displays it, Right? - LostDok
  • one
    Yes. Right! .......................... - zabachok

What if it is added to the layout?

  • No, I only need the variable on a few pages. If you add to the layout, it will be on all pages. - LostDok

Try an element with the order-event-btn class to write the url in the data attribute, and for $ .ajax, make the url: $ (this) .attr ('data-url'); It should be a universal solution for such elements.