How can I access PHP array inside my Javascript?

Viewed 1444

I have a very simple PHP array

$array = [];
$array['a'] = '1';
$array['b'] = '2';
$array['c'] = '3';

PHP

If I dd($array); out I got

array:3 [▼
  "a" => "1"
  "b" => "2"
  "c" => "3"
]

If I decode dd(json_encode($array));, I got this

"{"a":"1","b":"2","c":"3"}"

JS

I want to be able to access this variable in my Javascript, So I've tried


1

console.log($array);

I got

$array is not defined


2

I'm using Laravel. {{ }} == echo

console.log('{{$array}}');

I got

500 Internal Error

htmlentities() expects parameter 1 to be string, array given (View: /Users/bheng/Sites/portal/resources/views/cpe/index.blade.php)


3

console.log('{{ json_encode($array)}}');

I got

The page to load, but the data is very bad looking

{"a":"1","b":"2","c":"3"}


4

console.log(JSON.parse('{{ json_encode($array)}}'));

I got

Uncaught SyntaxError: Unexpected token & in JSON at position 1


5

console.log(JSON.parse('{{ json_decode($array)}}'));

I got

json_decode() expects parameter 1 to be string, array given


6

console.log('{{ json_decode($array)}}');

I got

json_decode() expects parameter 1 to be string, array given


GOAL

I just want to be able to access my array as Javascript Array or JSON in the Javascript.

Can someone please fill me in on this ?

4 Answers

In Blade, {{ $variable }} will output an escaped version of the string, passed through htmlentities() to make it safe for use in HTML. You want an unescaped version. You can use {!! $variable !!} for that:

console.log({!! json_encode($array) !!});

You don't need to add quotes around it, json_encode() outputs a valid javascript object. It will add quotes where necessary, if you add them yourself you will get the JSON string in your javascript, instead of the JSON object.

In Laravel you can use {!! !!} to skip entity escaping

console.log({!! json_encode($array) !!});

Just echo it as json data and use it in javascript.

<?php
  $array = [];
  $array['a'] = '1';
  $array['b'] = '2';
  $array['c'] = '3';
?>
<script>var jsArr = <?=json_encode($array);?>;
alert(jsArr);</script>

EDIT because of clarification that you're using blade. Then it should be:

<?php
  $array = [];
  $array['a'] = '1';
  $array['b'] = '2';
  $array['c'] = '3';
?>
<script>var jsArr = {!! json_encode($array) !!};
alert(jsArr);</script>

{ ... } is an escaped version of your string. But you need the unescapt string. This can be achieved by using {!! ... !!}.

First, you have to understand that PHP run on server side and javascript on client side, as PHP make the response you should print a script like this:

echo "<script>
var sheison = JSON.parse(".dd(json_encode($array)).");
console.log(sheison);
</script>";

I didn't test the code, is just the idea.

Related