简体   繁体   中英

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!

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>

Try this

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Payment Receipt</title>
</head>

<body>

<?php
...
if($row) {
    $myValue = 'Hi there!'
?>
<script>
var msg = "<?php $myValue; ?>";

</script>
<?php } else { 
  echo 'Incorrect Value';
}
?>
</body>
</html>

Simplifying your code (which you should always do when debugging!) you have this:

$myValue = 'Hi there!';
echo <<<JS001
<script type="text/javascript">
var msg = {$myValue};
</script>
JS001;

If you look at the HTML that's returned to the browser, you'll see that it looks like this:

<script type="text/javascript">
var msg = Hi there!;
</script>

The browser has no idea that "Hi there!" was supposed to be a string, so it tries to execute it as code.

What you wanted the output to be was this:

<script type="text/javascript">
var msg = 'Hi there!';
</script>

So we need to add those quote marks into the PHP:

$myValue = 'Hi there!';
echo <<<JS001
<script type="text/javascript">
var msg = '{$myValue}';
</script>
JS001;

As a more general solution, you can abuse the fact that JSON strings are valid JS values, and use json_encode in the PHP:

$myValue = 'Hi there!';
$myValueJson = json_encode($myValue);
echo <<<JS001
<script type="text/javascript">
var msg = {$myValueJson};
</script>
JS001;

This makes no difference in this case, but is useful for passing other types of value - arrays, null , etc

For a better code management, you should probably separate HTML, PHP, and JS code in different files.

Imagine something like this :

controller.php


$displayName="David";

include 'vue.php';

vue.php


<html>
...
<body>

<div id="php-data" data-displayName="<?php echo $displayName ?>"></div>

</body>
</html>

script.js

<script>
var msg = document.getElementById('php-data').dataset.displayName // "David";

</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM