3

I have a javascript function that I am calling in a php page. I also added a json method to this function that pulls data from the database. Here's what it looks like:

$this->registerJsFile('/js/restaurant-reserve.js', ['depends' => [JqueryAsset::class]]);
$this->registerJs('restaurantReserve.init('. Json::encode($restaurant->workHours) .')');

As a result, at the end of the page, I get this data in the form:

restaurantReserve.init([{"id":86,"restaurant_id":1,"day":"Mon","open":"9.30","close":"14.30","created_at":"2022-02-22 10:56:15"}])

But I want to use this data in the javascript file itself, where the restaurantReserve function is located.

Because now I have to do it manually:

let json = [{"id":86,"restaurant_id":1,"day":"Mon","open":"9.30","close":"14.30","created_at":"2022-02-22 10:56:15"}]

How can I make json data come to javascript so that I can use it? To not write it by hand.

update

One of the answers came up to me, it was to add this line, which will globally declare this variable:

$this->registerJs('let json = '. Json::encode($restaurant->workHours) .';');

But it turns out that this variable is declared after the execution of the script of this restaurant-reserve.js file where this variable is used, and I don’t understand a little how to make it higher.

Here is my final code in php file:

$this->registerJs('let json = '. Json::encode($restaurant->workHours) .';');
$this->registerJsFile('/js/restaurant-reserve.js', ['depends' => [JqueryAsset::class]]);
$this->registerJs('restaurantReserve.init()');

And what I get as a result on the page, first comes the file, then this variable:

<script src="/js/restaurant-detail.js"></script>
<script src="/js/share.js"></script>
<script>jQuery(function ($) { 
let json = [{"id"...}]
</script>

What can be done??

  • Hi mason and welcome to SO. Usually you would use the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) to get the JSON file or data from the server. – Emiel Zuurbier Apr 10 '22 at 12:43
  • @EmielZuurbier hi, I don't quite understand how to use it in my case –  Apr 10 '22 at 12:48
  • Well, you would write a PHP endpoint that only has one thing to do: present the JSON data. For example a URL like: `https://example.com/restaurant-reserve`. Visiting that URL should give you a JSON response. The endpoint could also be a php file: `https://example.com/restaurant-reserve.php`. That URL can then be called with `fetch`. Fetch is no more than manually doing an HTTP request, just like your images and CSS files are requested by the browser. But take it step by step, start by making the data accessible from a URL. Are you using a framework? – Emiel Zuurbier Apr 10 '22 at 13:06
  • @EmielZuurbier I am using yii2 –  Apr 10 '22 at 13:28
  • Then I would suggest looking at [this thread](https://stackoverflow.com/questions/41675051/get-response-in-json-format-in-yii2) and the docs of Yii2 on [requests](https://www.yiiframework.com/doc/guide/2.0/en/runtime-requests) and [responses](https://www.yiiframework.com/doc/guide/2.0/en/runtime-responses). I know there are tons of examples on the JavaScript part regarding `fetch` AKA AJAX. I'm not familiar with Yii2 when it comes to examples or tutorials, but this subject is so common, there must be an example. – Emiel Zuurbier Apr 10 '22 at 19:12

2 Answers2

1

You may add following line in the code

$this->registerJs('let json = '. Json::encode($restaurant->workHours) .';');

Updating the answer after reading your comments and further queries.

You may pass second one more parameters to registerJs function. View::POS_READY or View::POS_BEGIN

Like :

$this->registerJs('let json = '. Json::encode($restaurant->workHours) .';', View::POS_READY);
  • get `Uncaught ReferenceError: json is not defined` –  Apr 11 '22 at 15:52
  • this variable is declared in the script at the end of the page, but it needs to be in my file –  Apr 11 '22 at 15:53
  • And, probably this is because my file is executed first than this variable is declared –  Apr 11 '22 at 16:09
  • and I don't quite understand how to make this variable be higher than this file –  Apr 11 '22 at 16:35
  • I first declare these files, and then initializations go where this variable ends up ` ` ` –  Apr 11 '22 at 16:41
  • Thanks to @Shriram-Jadhav. I gave you an Upvote. I'm sorry. It was not possible to explain in the comments. In the new post ... – user206 Apr 11 '22 at 21:11
1

The second argument in registerJs is related to this issue.
That is, The second argument determines at which position the script should be inserted into the page. Possible values are:

View::POS_HEAD  for head section.
View::POS_BEGIN  for right after opening <body>.
View::POS_END  for right before closing </body>.
View::POS_READY  for executing code on the document ready event. This will automatically register jQuery and wrap the code into the appropriate jQuery code. This is the default position.
View::POS_LOAD  for executing code on the document load event. Same as the above, this will also register jQuery automatically.

The first argument is the actual JS code we want to insert into the page. It will be wrapped into a tag. The second argument determines at which position the script should be inserted into the page.

For scriptFiles you can also specify the place and time to load it. According to the dependencies and ....
It is better to refer to this link.

user206
  • 1,085
  • 1
  • 10
  • 15