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??