Are there best practices for formatting and organizing code to avoid issues with passing variables between PHP and JavaScript?

When passing variables between PHP and JavaScript, it is important to properly format and organize your code to avoid issues. One common best practice is to use JSON to encode variables in PHP before passing them to JavaScript. This ensures that the data is properly formatted and can be easily parsed on the JavaScript side.

<?php
// Encode a PHP variable into JSON format
$variable = 'Hello, World!';
$json_data = json_encode($variable);
?>

<script>
// Parse the JSON data in JavaScript
var jsonData = <?php echo $json_data; ?>;
console.log(jsonData);
</script>