right now I'm sending a json from laravel to the View and populating a form, the problem is that I need to do certain modifications based in that data from javascript. Right now I use an Ajax request to ask for the exact data from the server, I think thats a little repetitive, and I know I can do something like (var data = {{$data}}) and use it in my 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 make the variable from the view is a bad practice or not.
Thanks
To pass PHP variables and data to JavaScript, you need to make the data accessible to JavaScript. You can echo the data directly to JavaScript variable, or you can keep the data in the DOM before retrieving it using JavaScript Document object.
Javascript will be interpreted in Client's browser and you can not assign it to PHP variable which is interpreted on SERVER .
You can easily get the JavaScript variable value on the same page in PHP. Try the following codeL. <script> var res = "success"; </script> <? php echo "<script>document.
Laravel does not require you to use a specific JavaScript framework or library to build your applications. In fact, you don't have to use JavaScript at all. However, Laravel does include some basic scaffolding to make it easier to get started writing modern JavaScript using the Vue library.
Here is one solution to pass javascript variables. http://forumsarchive.laravel.io/viewtopic.php?id=2767
In 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 that 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 multiple approaches for this problem
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With