What are some common pitfalls when trying to integrate PHP and JavaScript code?

One common pitfall when integrating PHP and JavaScript code is not properly escaping PHP variables when injecting them into JavaScript code, which can lead to syntax errors or security vulnerabilities. To solve this issue, you can use PHP's json_encode function to safely encode PHP variables for use in JavaScript.

<?php
// Example PHP variable
$phpVariable = "Hello, world!";

// Encoding PHP variable for JavaScript use
$jsVariable = json_encode($phpVariable);
?>

<script>
// Using the encoded PHP variable in JavaScript
var message = <?php echo $jsVariable; ?>;
console.log(message);
</script>