I have a file named test.php which has this whole code :
<!DOCTYPE html>
<html lang="en">
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
...
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if($row) {
$obj->txndate = $row['date'];
$obj->txnid = $row['txnid'];
$obj->atomid = $row['atomid'];
$obj->amount = $row['amount'];
$myJSON = json_encode($obj);
echo $myJSON;
//javascript starts inside PHP
echo '<script>', PHP_EOL;
echo 'var msg = <?php echo json_encode($myJSON); ?>;', PHP_EOL;
echo 'var ThunkableWebviewerExtension = {', PHP_EOL;
echo 'postMessage: function (message) {', PHP_EOL;
echo 'if (window.ReactNativeWebView) {', PHP_EOL;
echo 'window.ReactNativeWebView.postMessage(message);', PHP_EOL;
echo '} else {', PHP_EOL;
echo 'window.parent.postMessage(message, '*');', PHP_EOL;
echo '}', PHP_EOL;
echo '}', PHP_EOL;
echo '}', PHP_EOL;
echo 'ThunkableWebviewerExtension.postMessage(msg);', PHP_EOL;
echo '</script>', PHP_EOL;
} else {
echo 'Incorrect ID';
}
$conn->close();
?>
</body>
</html>
When I run this code, nothing happens in the JavaScript side - everything works well until the JavaScript starts. This is the JavaScript code I tried to embed in the PHP code :
<!DOCTYPE html>
<html>
<body>
<?php
$myJSON = 'Hi there!';
?>
<script>
var msg = <?php echo json_encode($myJSON); ?>;
var ThunkableWebviewerExtension = {
postMessage: function (message) {
if (window.ReactNativeWebView) {
window.ReactNativeWebView.postMessage(message);
} else {
window.parent.postMessage(message, '*');
}
}
}
ThunkableWebviewerExtension.postMessage(msg);
</script>
</body>
</html>
The above code works well as expected when I run it separately in a different file, which too has the PHP variable passed in the var msg command.
I wonder what I did wrong trying to write JavaScript code inside PHP - I saw somewhere that by echoing the statement, then adding PHP_EOL at the end we can write JS/HTML in-between PHP.
What's wrong here? Any help would be appreciated!