I'm scripting a small RP game Text base. I found a site with chance.js script free to use but I am trying to find out how to use it within PHP.
This is the code they tell you to use:
<script src="chance.js"></script>
<script>
console.log(chance.bool());
</script>
But every time I put it in my PHP it blacks out everything and does not work. I have tried to search everywhere to try and find out why but found nothing. A lot of sites say I can't use JavaScript in PHP, but I know that can't be true.
Please, someone point me in the right direction... :)
P.S. the replay with be true or false http://chancejs.com/ <<< is the site it's from.
PHP != JavaScript. JavaScript is client-side and PHP is server-side.
You might want to use rand()
to generate random numbers.
If you want to output this into browser do it either as:
<?php
...
?>
<script src="chance.js"></script>
<script>
console.log(chance.bool());
</script>
<?php
...
?>
or use the echo php function:
echo '<script src="chance.js"></script>
<script>
console.log(chance.bool());
</script>';
To echo JavaScript inside of PHP, you should do this:
<?php
echo"
<script src='chance.js'></script>
<script>
console.log(chance.bool());
</script>
";
?>
Also, notice that I echoed it inside of double quotes, this means that now if you use double quotes inside of your JS you should escape them like this: \"
.
As stated in a previous answer, you should be very careful about mixing PHP with JavaScript, as PHP is always executed before JS.