Marco Marco - 7 months ago 70
PHP Question

PHP Vars to JavaScript Laravel 5.2

I am using this package to pass variables to javascript in Laravel 5.2, but I get:


all.js:56Uncaught ReferenceError: categories is not defined


In my controller I am trying to pass variables like this:

JavaScript::put([
'categories' => $numberOfViewsByCategory[0],
'categoryViews' => $numberOfViewsByCategory[1],
'chains' => $numberOfViewsByChain[0],
'chainViews' => $numberOfViewsByChain[1]
]);


I have set the path in the config file:

'bind_js_vars_to_this_view' => 'layouts.partials.foot',


And my partials.foot blade looks like this:

@section('foot')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js" integrity="sha384-I6F5OKECLVtK/BL+8iSLDEHowSAfUo76ZL9+kGAgTRdiByINKJaqTPH/QVNS1VDb" crossorigin="anonymous"></script>
<script type="text/javascript" src="{{ asset('js/zurb/zurb.js') }}"></script>
<script type="text/javascript" src="{{ asset('js/jquery-ui/jquery-ui.min.js') }}"></script>
<script src="//cdn.tinymce.com/4/tinymce.min.js"></script>
<script type="text/javascript" src="{{ asset('js/jquery-filer/jquery-filer.js') }}"></script>
<script type="text/javascript" src="{{ asset('js/editor/editor.js') }}"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"> </script>
<script src="{{ asset('js/all.js') }}"></script>
@stop


But when I do console.log(categories) in my all.js file, I get the above mentioned error.

Answer

the documentation says:

which view you want your new JavaScript variables to be prepended to.

So I suppose that in your layout.blade.php you have something like @yield('footer') for the moment.

I would suggest editing your foot.blade.php like:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js" integrity="sha384-I6F5OKECLVtK/BL+8iSLDEHowSAfUo76ZL9+kGAgTRdiByINKJaqTPH/QVNS1VDb" crossorigin="anonymous"></script>
<script type="text/javascript" src="{{ asset('js/zurb/zurb.js') }}"></script>
<script type="text/javascript" src="{{ asset('js/jquery-ui/jquery-ui.min.js') }}"></script>
<script src="//cdn.tinymce.com/4/tinymce.min.js"></script>
<script type="text/javascript" src="{{ asset('js/jquery-filer/jquery-filer.js') }}"></script>
<script type="text/javascript" src="{{ asset('js/editor/editor.js') }}"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js">  </script>
<script src="{{ asset('js/all.js') }}"></script>

And in your layout, to replace the @yield by an @include('partials.foot')