-1

I need to echo a PHP variable into JavaScript. But I have no experience about JavaScript, I did some research but nothing worked for me.

The code

 function hide() {
   document.getElementById("myDiv").style.display="none";
   <?php echo $myVar; ?>
 }

And the $myVar looks like:

$myVar = "Hi there";
halfer
  • 19,824
  • 17
  • 99
  • 186

4 Answers4

0

you can do like this in js :

var php_val = '<?php echo $myVar; ?>';
 alert(php_val);
Mahmood Rehman
  • 4,303
  • 7
  • 39
  • 76
0
<?php $var="blah"; ?>
 <script type="text/javascript">
 alert('<?php echo $var ?>');
 </script>
halfer
  • 19,824
  • 17
  • 99
  • 186
r3wt
  • 4,642
  • 2
  • 33
  • 55
0

use this

$myVar = 'var myVar="Hi here"'

or

function hide() {
   document.getElementById("myDiv").style.display="none";
   var myVar='<?php echo $myVar; ?>'
 }
Stark
  • 31
  • 3
0

There is 2 ways to write PHP variable in javascript:

First Way:

JavaScript written in the php page or inline:

EX:

<?php 
   $myVar = 'hello';
?>
....
<script>
function hide() {
   document.getElementById("myDiv").style.display="none";
   <?php echo $myVar; ?>
}
</script>

Second way:

Put your variables on the top of your page, like baseUrl for example, and use it in separated JavaScript file but you have to write the variables before load JavaScript files.

EX:
<head>
<script>
    var baseUrl = <?php echo $thisPageUrl; ?>
</script>
</head>
....

<script src="myscriptfile.js"></script>
Abudayah
  • 3,816
  • 7
  • 40
  • 60