PHP Controller array to Javascript?

Silverstripe Version: 4.9

Question: Is there a way to pass a PHP array from controller to Javascript?

Hi, is there a way to pass a whole array from the controller to Javascript? So far I have been using javascriptTemplate to pass variables to JS, but javascriptTemplate only takes either integers or strings. Since my data for the array is taken through a SQL query, it is dynamic and I cannot pass variables as it will be different every time.

Thank you!

$data = [];

foreach ($query as $row) {
    array_push($data, [
        'ID' => $row['id'],
        'Name' => $row['name']

$vars = [
    "Data" => $data

// Here it will give an error "Expected parameter of type 'int[]|string[]', 'array[]' provided"
Requirements::javascriptTemplate("location/file.js", $vars);

Javascript has no idea what a PHP array is or how to handle it. You need something that Javascript is going to be able to parse / iterate, so you can build a javascript array as a string, or json encode your PHP array and pass that in.

If you need more dynamic data, then you may need to look at adding a specific endpoint on your controller which can be queried by your JS via AJAX, using something like Vue, etc.