<!DOCTYPE html>
<html lang="en">
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
...
if($row) {
$myValue = 'Hi there!';
?>
<script>
var msg = "<?php echo $myValue; ?>"; //trying to set it to a JS var, so I could send it to below
//Your remaining js script here ...
</script>
<?php } else {
//your else condition
}
?>
</body>
</html>
<script>
var msg = document.getElementById('php-data').dataset.displayName // "David";
</script>
Problem :
I have the below piece of code in my test.php file. The code mainly has a variable defined in PHP, and I want to send it to a JavaScript function so it could POST it. Here’s the code :
<!DOCTYPE html>
<html lang="en">
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
...
if($row) {
$myValue = 'Hi there!'; //the PHP variable (currently has a sample value, but will be string only)
//JS starts
echo <<<JS001
<script type="text/javascript">
var msg = {$myValue}; //trying to set it to a JS var, so I could send it to below function.
var ThunkableWebviewerExtension = {
postMessage: function (message) {
if (window.ReactNativeWebView) {
window.ReactNativeWebView.postMessage(message);
} else {
window.parent.postMessage(message, '*');
}
}
};
ThunkableWebviewerExtension.postMessage(msg);
console.log(msg);
alert('Message Sent');
</script>
JS001;
} else {
echo 'Incorrect Value';
}
?>
</body>
</html>
But when I run this code, I get this error on console : Uncaught SyntaxError: Unexpected identifier. What should I do if I want to send just a simple string value to the JS code? What’s wrong currently?
Any help is appreciated! Thanks!
Comments
Comment posted by BigSantuary
Thanks, @mPareek! I just want to confirm two things – 1) I see you haven’t put a semicolon at the end of
Comment posted by Manish Pareek
#1 Oh, it was a typo. I missed it. You can put it there. #2 NO it would not cause any errors.
Comment posted by BigSantuary
Thanks. my JS function would also be there in the
Comment posted by BigSantuary
Thanks, I’ll check and see if this code works for me.
Comment posted by Manish Pareek
@BigSantuary Please note I have added
Comment posted by Manish Pareek
How does it make sense to post exactly the same answer as I did? If you want to contribute provide some other way to do it.
Comment posted by chyke007
If you look clearly it is not the same answer, , yours misses a semi colon
Comment posted by BigSantuary
Thanks, @chyke007! Do I need to add that semicolon after
Comment posted by Manish Pareek
@BigSantuary technically it will not matter unless you write something after that. But I recommend you to put it for uniformity and avoid confusions(like we are having now 🙂 ).
Comment posted by chyke007
Added it to show how it is done incase a second statement is needed.