2

I have this php var, and I want to send it to php, but this way I can't

<?php
    $nb = rand(1,68);
?>
///////////////////////////////////////////////////////////////////////////
<script type="text/javascript"> jQuery ( '#dwDB-main' ).fadeTo ( 1, 0.01 );
    function random() {
    $rd = <?php $nb ?>;
    return $rd;
    }
Zé Pedro
  • 31
  • 4
  • 1
    Well, $rd isn't how you define a variable in javascript; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var – IsThisJavascript Oct 20 '17 at 08:48
  • After all the fixes from other comments, your random() will still not return random number as you expected. It will always return the value it initially retrieved from PHP. You'd better use javascript Math.random() to really generate random number in javascript. – Anurat Chapanond Oct 20 '17 at 08:51

3 Answers3

1
function random() {
    var rd = <?= $nb ?>;
    return rd;
}
Thielicious
  • 4,122
  • 2
  • 25
  • 35
0

use echo for transfer the variable statement, actually its not able to print

<?php
$nb = rand(1,68);
?>
///////////////////////////////////////////////////////////////////////////
<script type="text/javascript"> jQuery ( '#dwDB-main' ).fadeTo ( 1, 0.01 );
    function random() {
        var $rd = <?php echo $nb; ?>;
        return $rd;
    }
0

Try this.

<?php
    $nb = rand(1,68);
?>

<script type="text/javascript"> 
    function random() {
    var rd = <?php echo $nb ?>;
        return rd;
    }
    console.log(random());
</script>

And remember if you are using jquery then please add jquery script also.

Mubashar Iqbal
  • 398
  • 7
  • 18