3

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>)
8
  • Check the actual output in the page. What does the JS code look like? Debug it from there Commented Mar 20, 2019 at 9:29
  • 3
    Possible duplicate of Convert php array to Javascript Commented Mar 20, 2019 at 9:29
  • @RoryMcCrossan I am only getting the Laravel error output Commented Mar 20, 2019 at 9:34
  • In which case case you should Google the error. It leads to this: stackoverflow.com/q/43217872/519413 Commented Mar 20, 2019 at 9:38
  • @RoryMcCrossan I have updated my question. Commented Mar 20, 2019 at 9:44

2 Answers 2

7

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 &quot; 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.

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

10 Comments

Thank you for your answer. I am now getting the error "jQuery.Deferred exception: Unexpected token & in JSON at position 2 SyntaxError: Unexpected token & in JSON at position 2"
You're welcome, That happens because "$users" isn't an array it's a collection.
Okay. Kindlyy explain how I can convert it from an collection to an array
Thank you very much Zakaria. It works! Please please explain what just happened
Ok. Noted. Thanks again Zakaria
|
-2
var dataSet = @php $chequesArray @endphp;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.