What are the best practices for using onclick functions in PHP to interact with JavaScript?

When using onclick functions in PHP to interact with JavaScript, it is important to properly escape any dynamic data being passed to the JavaScript function to prevent XSS attacks. One common way to achieve this is by using the json_encode function in PHP to safely encode the data before passing it to the JavaScript function.

<?php
$dynamic_data = "<script>alert('XSS attack!');</script>";
$escaped_data = json_encode($dynamic_data);
?>
<button onclick="myFunction(<?php echo $escaped_data; ?>)">Click me</button>