0

I am trying to display a PHP array in a JavaScript function.

function displayinfo(id){
     var array = [ {{ $infoarrayFromController[id] }} ]; 
     }

Here, as the id is supposed to be received from the select option in the form, and the respective information is supposed to be displayed.

The problem I am facing is that I am not able to pass the variable into the array.

The error I got: enter image description here

Cherryl Rarewings
  • 618
  • 1
  • 5
  • 13
  • I got that backwards; you can't use the JS variable `id` in a PHP array; PHP processed long before `id` is available. You could convert `$infoarrayFromController` to a JS variable, like `var jsArray = JSON.parse('{{ $infoarrayFromController }}')`, then `jsArray[id]` should work. – Tim Lewis Feb 02 '22 at 19:46
  • 2
    You'd need to send a http request to a php page with the id, and let php build the array and return it as a response. – James Feb 02 '22 at 19:47
  • As James stated, the best way would be to call a PHP script. You can also use something like this: https://github.com/laracasts/PHP-Vars-To-Js-Transformer. You can also echo PHP vars in javascript, it depends what is the content of your variable in your example. – Mtxz Feb 02 '22 at 22:46

0 Answers0