-5

I have an php variable contains string, got from a function, and wants to view it in alert message in javascript, well, I tried to that

    var tmp='<?php echo $BillMsg; ?>';
    alert(tmp);

But the alert didn't show up, in the console I found this error Uncaught SyntaxError: Unexpected token ILLEGAL

I tried to define a random php variable like the follwoing

    <?php $test="test";?>
    <script> alert(<?php echo $test; ?>); </script>

It works fine, but when using the variable $BillMsg, it won't work? Whats wrong?

mplungjan
  • 155,085
  • 27
  • 166
  • 222
Omar Taha
  • 245
  • 2
  • 14

3 Answers3

1

The error you see is a JS error, which means that either there's a problem with your JS code (perhaps some other part of the front end code you're not showing us is flawed). Alternatively, the PHP value is causing problems. The way to easily insert PHP values in JS is through JSON:

var tmp = <?= json_encode($someVar); ?>;
//<?= is short for <?php echo
alert(tmp);

That shouldn't cause any trouble, no matter what the value of $someVar is.
With your updated code snippet, the issue is that the value of $test is not being quoted when passed to the alert function. Change it to this, and it'll work:

<?php $test="test";?>
<script> alert(<?= json_encode($test); ?>); </script>
Elias Van Ootegem
  • 70,983
  • 9
  • 108
  • 145
0

try this..

<html>
<head>
    <script>
        function msg1(){
        var msg = document.getElementById('msg').innerHTML;
        alert(msg);
    }
    </script>
</head>
<body>
    <?php
       echo "<p id='msg'>Here is my string</p>";
    ?>
    <input type="button" onclick="return msg1();" value="button"/>
</body>

Vishal
  • 46
  • 4
-3

what about this

<?php 
$BillMsg = isset($BillMsg)? $BillMsg : "$BillMsg not set";
?>
var tmp='<?php echo $BillMsg; ?>';
    alert(tmp);
hdl_07z
  • 1
  • 3