2

I would like to assign json object to the jquery variable. But when i try it i get error:

htmlentities() expects parameter 1 to be string, object given (View: /var/www/html/resources/views/index.blade.php)

What's the easy way to do this? Here is my code:

        var data = {};
        data = "{{$stationData}}";
yigitozmen
  • 947
  • 4
  • 23
  • 42

4 Answers4

3

You could do this by json encoding the PHP variable within your JavaScript. This will only work with inline JavaScript code, like so:

<?php
$foo = 'bar';
?>
<script>
    var foo = <?php echo json_encode($foo) ?>;
<script>

Another option to pass data from the backend to the front-end is by using AJAX. This SO answer explains how this is done with and without jQuery.

Community
  • 1
  • 1
JasonK
  • 5,214
  • 9
  • 33
  • 61
3

In Laravel 5 and above it's:

data = {!! str_replace("'", "\'", json_encode($stationData)) !!};

in Laravel 4

data = {{{ str_replace("'", "\'", json_encode($stationData)) }}};

You need to escape this format twice. Otherwise can act strangly.

Filip Koblański
  • 9,718
  • 4
  • 31
  • 36
1
data = {{json_encode($stationData)}};
huuuk
  • 4,597
  • 2
  • 20
  • 27
0

$stationData beeing an Eloquent object, you could do something like this:

var foo = {{$stationData->toJson()}}

or any of the other answers.

PlayMa256
  • 6,603
  • 2
  • 34
  • 54