Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to send from php a variable to javascript, using laravel

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

like image 418
LuisKx Avatar asked Feb 11 '14 20:02

LuisKx


People also ask

Can I pass a variable from PHP to JavaScript?

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.

Can we assign JavaScript variable to PHP variable?

Javascript will be interpreted in Client's browser and you can not assign it to PHP variable which is interpreted on SERVER .

How use JavaScript variable on same page in PHP?

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.

Can I use JavaScript in laravel?

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.


1 Answers

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

like image 178
zainengineer Avatar answered Oct 05 '22 20:10

zainengineer