Best way to send from php variable to javascript using laravel

right now I'm sending json from laravel to View and filling out the form, the problem is that I need to make some changes based on this data from javascript. Right now I am using an Ajax request to request accurate data from the server, I think it is a bit repetitive, and I know that I can do something like (var data = {{$ data}}) and use it in the js file.

My question is: what is the best solution? Make an ajax call or make the variable directly from the view, I don't know if the variable from the view makes bad practice or not.

thanks

+7
javascript ajax php laravel
source share
1 answer

Here is one solution for passing javascript variables. http://forumsarchive.laravel.io/viewtopic.php?id=2767

In the controller

// controller $js_config = array( 'BASE' => URL::base(), 'FACEBOOK_APP' => Config::get('application.facebook_app') ); return View::make('bla') ->with('js_config', $js_config); 

In view

 <script> var config = <?php echo json_encode($js_config) ?>; alert(config.BASE); alert(config.FACEBOOK_APP.id); alert(config.FACEBOOK_APP.channel_url); </script> 

Libraries are also available for this purpose.

https://github.com/laracasts/PHP-Vars-To-Js-Transformer

 public function index() { JavaScript::put([ 'foo' => 'bar', 'user' => User::first(), 'age' => 29 ]); return View::make('hello'); } 

There are several approaches to this problem.

+8
source share

All Articles