How can I access a PHP array inside my Javascript?

I have a very simple PHP array

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

Php

If I dd($array); came out i got

 array:3 [โ–ผ "a" => "1" "b" => "2" "c" => "3" ] 

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

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

Js

I want to have access to this variable in my Javascript, so I tried


1

console.log ($ array);

I got

$ array not defined


2

I am using Laravel. {{ }} == echo

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

I got

500 Internal Error

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


3

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

I got

Page to load, but the data looks very bad

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


4

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

I got

Untrained 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 the string given by the array


6

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

I got

json_decode () expects parameter 1 to be the string given by the array


TASK

I just want to have access to my array as a Javascript Array or JSON in Javascript.

Can someone please fill me in?

+5
source share
4 answers

Blade {{ $variable }} displays an escaped version of the string that passed through htmlentities() to make it safe for use in HTML. You want an unlimited version. You can use {!! $variable !!} {!! $variable !!} for this:

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

You do not need to add quotes around it, json_encode() outputs a valid javascript object. Add quotes if necessary, if you add them yourself, you will get a JSON string in your javascript instead of a JSON object.

+6
source

In Laravel, you can use {!!!} to skip an object exception

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

Just repeat 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 due to the fact that you are using a 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 a unescapt string. This can be achieved using {!! ... !!}.

0
source

Firstly, you should understand that PHP works on the server side and javascript on the client side, since PHP does the answer, you should print the script as follows:

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

I have not tested the code, this is just an idea.

0
source

Source: https://habr.com/ru/post/1272022/


All Articles