Skip to content
Advertisement

Parse Laravel JSON object in Javascript throwing error

Laravel code :

$teachers = Teachers::where('possessed_by_community', $communityId)->pluck('teacher_name');

return view('pages.show_add_teachers', [
    'teachers'  => $teachers
]);

Then in client side I tried :

var teachers = "<?php echo json_encode($teachers) ?>" ;
teachers = JSON.parse(teachers);
console.log(teachers);

In webconsole I get :

SyntaxError: missing ; before statement

In firefox debugger :

enter image description here

Advertisement

Answer

Use single quotes instead var teachers = '<?= json_encode($teachers) ?>';

or don’t use quotes at all, leaving out JSON.parse(teachers);.

var teachers = <?= json_encode($teachers) ?>;
console.log(teachers);

Though you must check $teachers is valid, string, null or array at all times.

Else it would become var teachers = ; and break.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement