Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access 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); 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 ?

like image 756
code-8 Avatar asked Sep 21 '17 18:09

code-8


People also ask

Can I use PHP array in JavaScript?

You can use PHP array in JavaScript. It works for the single as well as the multidimensional array. Use the json_encode() method to achieve this.

How do I browse an array in JavaScript?

JavaScript Array indexOf() The indexOf() method searches an array for an element value and returns its position. Note: The first item has position 0, the second item has position 1, and so on.

Can we have array inside array in JavaScript?

JavaScript lets us create arrays inside array called Nested Arrays. Nested Arrays have one or many arrays as the element of an array.

How are PHP arrays accessed?

The elements in a PHP numerical key type array are accessed by referencing the variable containing the array, followed by the index into array of the required element enclosed in square brackets ([]).


1 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.

like image 155
rickdenhaan Avatar answered Sep 24 '22 01:09

rickdenhaan