2

I want to pass php array in javascript code . when i use like this:

var resData = "{{ json_encode($data['calendarItems']) }}";

or this :

 var resData = "{{ $data['calendarItems'] }}";

in both the result is :

[{"title":"rfvd vc","expired_at":"2018-12-31 00:00:00"}] //formatting

and JSON.parse return error. I can not get the array

Sanjit Bhardwaj
  • 893
  • 7
  • 13
Zahra Badri
  • 1,656
  • 1
  • 17
  • 28

3 Answers3

1

There's two issues here. The first is that you're quoting the json output and the second is that the result is escaped to html entities.

Remove the quotes and output the result in raw format:

var resData = {!! json_encode($data['calendarItems']) !!};

Omitting the quotes around the result will remove the need to use JSON.parse(), since the variable will contain proper json from the start.

Read more about unescaped data in blade in the manual

M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
  • It may be worth adding the difference between displaying json in script tags and json in attributes (where it does require escaping) https://stackoverflow.com/questions/4227895/html-entities-inside-script-tag-not-converted – Travis Britz Feb 12 '19 at 06:51
1

When you do {{ }} it converts string elements inside into html entities. so { will be converted to "

I will suggest to use this package, which has cleaner implementation of passing data as usable js variables in your blade file.

Mihir Bhende
  • 8,677
  • 1
  • 30
  • 37
1

You can try this:

var mapData = JSON.parse('<?php echo json_encode($latLng) ?>');

where $latLng is a PHP array.

Dinesh Suthar
  • 853
  • 1
  • 17
  • 41
  • There's no need to use `JSON.parse()` here. Just output the response from PHP without the quotes and it will already be valid json. – M. Eriksson Feb 12 '19 at 09:11