Example of the php code
Is there a solution for the implementation the two codes PHP + JS using ajax request
An alternative solution might be for the PHP code to send back the name of a script file which you can then add to your page.
I guess an example could be, if you're using ajax with the GET method,
$x = $_GET['x']
document.write(\\"" . $x . "\\");