Php Variable Into Javascript Variable

What’s the notation to redefine a php variable as a javascript variable?

<?php
include 'connect_to_mysql.php';
$results = mysql_query("SELECT * FROM plan WHERE TIMESTAMP(NOW()) < TIMESTAMP(end)") or die(mysql_error());
$phpVar = mysql_num_rows($results);
 
echo '<script type="text/javascript">';
echo 'var x  = ???????????';
echo 'document.write("<p>" + x + "</p>")';
echo '</script>';
?>

What’s the notation to redefine a php variable as a javascript variable?

<script type="text/javascript">

var myJsVar = <?php  echo $myPhpVar; ?> ;

</script>

Thanks.

Is there a way to code the whole script in php (just wondering)?

<?php
include 'connect_to_mysql.php';
$results = mysql_query("SELECT * FROM plan WHERE TIMESTAMP(NOW()) < TIMESTAMP(end)") or die(mysql_error());
$myPhpVar = mysql_num_rows($results);

echo '<script type="text/javascript">';
echo 'var myJsVar  = ???????????';
echo 'document.write(myJsVar)';
echo '</script>';
?>

echo 'var myJsVar  = '.$myPhpVar;

Can’t get it to work. Seems pretty straight forward. Any ideas?


<?php
$myPhpVar = 15;
echo '<script type="text/javascript">';
echo 'var myJsVar  = ' . $myPhpVar;
echo 'document.write(myJsVar)';
echo '</script>';
?>

You just need to do some basic debugging.

Have a look at the js code generated by the php in your browser and the error should then be obvious.

Page source says: <script type=“text/javascript”>var myJsVar = 15document.write(myJsVar)</script>

Looks like I’m just echoing strings.

Then, how should I format the javascript echos to keep the code all php?

you need to put either a semi-colon or new line char (preferably a semi-colon) at the end of your js generated by php in order to separate the individual js statements.

I thought that’s what I did:


<?php
$myPhpVar = 15;
echo '<script type="text/javascript">';
echo 'var myJsVar  = ' . $myPhpVar;
echo 'document.write(myJsVar)';
echo '</script>';
?>

What do you mean?

In this line here

echo 'var myJsVar  = ' . $myPhpVar;

the semi-colon at the end is just the normal mandatory semicolon at the end of the php echo statement. It doesn’t output a semi-colon at the end of the js code that the echo statement generates. Your echo statement needs to output a semi-colon at the end of the js statement it generates.

Zehr gut!

echo 'var myJsVar = ’ . $myPhpVar . ‘;’;

Thanks webdev1958.

Niche

well done - glad it’s finally sorted :slight_smile:

I’m going for a :drink: