7

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

2
  • I think you should make the question a little clearer and include your code so we can see what your trying to accomplish Commented Feb 11, 2014 at 22:01
  • I'm between doing this: <script type="text/javascript"> var info = {{$dist}}; //Here I declare the variable info that I use in my js file. </script> OR do this: $.getJSON(location.href, { ajax: 'true' }, function(json, textStatus) { var info = json[0]; //Same variable What is the best practice? Commented Feb 12, 2014 at 13:22

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.