What are the best practices for handling data retrieved from a database for use in JavaScript?

When handling data retrieved from a database for use in JavaScript, it is important to properly sanitize and format the data to prevent any security vulnerabilities or unexpected behavior. One common approach is to encode the data in JSON format before sending it to the client-side JavaScript code.

<?php

// Retrieve data from the database
$data = [
    'name' => 'John Doe',
    'age' => 30,
    'email' => 'johndoe@example.com'
];

// Encode the data in JSON format
$json_data = json_encode($data);

// Output the JSON data
echo "<script>var jsonData = $json_data;</script>";

?>