Skip to content
Advertisement

How to send a normal variable’s value from PHP to JavaScript?

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!

Advertisement

Answer

You can do:

<!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>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement