Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JavaScript to display Laravel's Variable

In my code I am using typeahead.js. I use Laravel 5 and I need to replace the var states with my {{ $jobs }} variable. I need to list all Job Titles as an array.

In my controller I have

$jobs = Job::all(['job_title']);

I know the loop method in javascript but I dont know how to "link" my blade's variable in the javascript. Anyone knows how to?

I have tried, in my.js

var jobs = {{ $jobs }}

But that wont work.

like image 337
Sylar Avatar asked Mar 27 '15 19:03

Sylar


5 Answers

For more complex variable types like arrays your best bet is to convert it into JSON, echo that in your template and decode it in JavaScript. Like this:

var jobs = JSON.parse("{{ json_encode($jobs) }}");

Note that PHP has to run over this code to make it work. In this case you'd have to put it inside your Blade template. If you have your JavaScript code in one or more separate files (which is good!) you can just add an inline script tag to your template where you pass your variables. (Just make sure that it runs before the rest of your JavaScript code. Usually document.ready is the answer to that)

<script>
    var jobs = JSON.parse("{{ json_encode($jobs) }}");
</script>

If you don't like the idea of doing it like this I suggest you fetch the data in a separate ajax request.

like image 129
lukasgeiter Avatar answered Nov 19 '22 20:11

lukasgeiter


This works for me

jobs = {!! json_encode($jobs) !!};

Notice

Only use this method if you can guarantee that $jobs contains no user input values. Using {!! ... !!} outputs values without escaping them which could lead to cross-site scripting (XSS) attacks.

like image 38
Karim Samir Avatar answered Nov 19 '22 21:11

Karim Samir


in laravel 6 this works for me

using laravel blade directive

var jobs = {!! json_encode($jobs) !!};

also used @json directive

var jobs = @json($jobs);

using php style

 var jobs = <?php echo json_encode($jobs); ?>
like image 45
Jignesh Joisar Avatar answered Nov 19 '22 19:11

Jignesh Joisar


Just to add to above :

var jobs = JSON.parse("{{ json_encode($jobs) }}");

will return escaped html entities ,hence you will not be able to loop over the json object in javascript , to solve this please use below :

var jobs = JSON.parse("{!! json_encode($jobs) !!}");

or

var jobs = JSON.parse(<?php echo json_encode($jobs); ?>);

like image 5
Jimmy Obonyo Abor Avatar answered Nov 19 '22 20:11

Jimmy Obonyo Abor


In laravel 7 I just do

var jobs = '{{ $jobs }}';
like image 4
Saddan Avatar answered Nov 19 '22 21:11

Saddan