-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
  • 169,008
  • 28
  • 173
  • 236
Omar Taha
  • 265
  • 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
  • 74,482
  • 9
  • 111
  • 149
  • @user3710166: You're welcome, but please: read the help section. If an answer to your question was helpful/fixed your problem, you are asked not to leave _"thanks"_ comments, but rather mark that answer as accepted – Elias Van Ootegem Jun 18 '14 at 07:40
  • Thanks again, I'm new to stack overflow, and I tagged the answer as accepted :) – Omar Taha Jun 18 '14 at 07:48
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