In my controller, I have an array store in this variable $month_g
dd($month_g);
I got
array:12 [▼
0 => array:2 [▼
"up_bytes" => 277664452
"down_bytes" => 198868462
]
1 => array:2 [▼
"up_bytes" => 0
"down_bytes" => 0
]
2 => array:2 [▶]
3 => array:2 [▶]
4 => array:2 [▶]
5 => array:2 [▶]
6 => array:2 [▶]
7 => array:2 [▶]
8 => array:2 [▶]
9 => array:2 [▶]
10 => array:2 [▶]
11 => array:2 [▶]
]
return view('page.index', get_defined_vars());
I want to be able to access this variable in my JS/View.
index.blade.php
I've tried
@extends('layouts.internal.master')
@section('content')
..... // content in HTML
@stop
@section('pagescripts')
<script>
console.log('{{$month_g}}');
</script>
@stop
I kept getting
htmlentities() expects parameter 1 to be string, array given
But console.log() is capable of printing out an array.
How do I console.log
that out ? What did I miss here ?
What is the best way to access controller variables within Javascript ?
If $month_g
is a PHP array, you want to first convert it to JSON so that javascript can use it.
<script>
var month_g = <?php echo json_encode($month_g) ?>;
console.log(month_g);
</script>
PHP's json_encode
method is the safest way to output PHP variables to be javascript variables in general. Even if you think the variable is an integer or simple string, json_encode
it anyway just to be safe.
Side note, you can also use Laravel's way instead of PHP tags if you prefer. Just note you need to use {!!
instead of {{
so that the output isn't escaped.
<script>
var month_g = {!! json_encode($month_g) !!};
Try json_encode()
return view('page.index', ['month_g' => json_encode($month_g)];
and from your view
@section('pagescripts')
<script>
console.log('{!! $month_g !!}');
</script>
@stop