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}}";

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

1
data = {{json_encode($stationData)}};

Comments

0

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

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

or any of the other answers.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.