I would like to assign an array from Laravel to a JavaScript array. I have gotten the array from my AppServiceProvider and json_decoded it like:
View::composer('*', function($view)
{
$users = Users::all();
$view->with(compact(users );
}
I then access my $usersArray from my javascript file like:
var dataSet = JSON.parse({!!$users !!});
I am however getting the following error;
jQuery.Deferred exception: Unexpected token o in JSON at position 1 SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
Since you're encoding it in the server side, you need to decode it in the client side like:
$chequesArray = Users::all()->toJson();
var dataSet = JSON.parse({!!json_encode($chequesArray)!!});
Or also Using "base64_encode" to conserve the json format like:
$chequesArray = base64_encode(Users::all()->toJson());
var dataSet = JSON.parse(atob('{{$chequesArray}}');
The main difference comes from the use of {{ }} vs {!! !!}, the first one escapes the special chars so it will turn the quotes "" to " then the JS will be unable to parse the string (that why we can use `base64_encode``to conserve the format), the second one will conserve the format and allow the quotes what gives the JS part the ability to parse it simply.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With