1

Here's javascript code that i have

  var randomnum = 30;

and here's PHP code

<?php $_SESSION['numbertoguess'] = '<script>document.write(randomnum)</script>';?>

But this is not passing the value But when i am trying this code below, it works. It gives session variable that the value 'a sample thing'.

<?php $_SESSION['numbertoguess'] = 'a sample thing';?>
Ronit Mukherjee
  • 405
  • 2
  • 10
Shrey
  • 93
  • 3
  • 5
  • 12
  • 3
    you are confused about the differences between client and server side programming. The way out i know is by using `AJAX` – Rotimi Nov 28 '17 at 02:17
  • https://stackoverflow.com/questions/21721461/use-javascript-variable-in-php-code – UghThatGUyAgain Nov 28 '17 at 02:19
  • You can't but this will be helpful https://stackoverflow.com/questions/2338942/access-a-javascript-variable-from-php – Casper Nov 28 '17 at 02:21
  • @Shrey You want to use JS variable in PHP? Asking for clarification. – Ronit Mukherjee Nov 28 '17 at 02:39
  • yes. Trying to give javascript value to session variable of php. HELP PLEASE!!! @RonitMukherjee – Shrey Nov 28 '17 at 02:56
  • @Shrey this is not the correct approach. You should use AJAX to send data from JS to PHP and vice-versa. But I would like to know what's your complete code? What's the code to create the random number? Why you are not wryiring the logic directly in PHP. – Ronit Mukherjee Nov 28 '17 at 03:01

2 Answers2

1

Look at the following code. The PHP session is assigned to 30 from the Javascript value. however am not sure if this is good way for implementation.

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Html Page Title</title>
</head>

<body>

    <script>
        var randomnum = 30;
     </script>

    <?php $_SESSION['numbertoguess'] = '<script>document.write(randomnum)</script>';?>
    <?php echo $_SESSION['numbertoguess']; ?>
</body>
</html>
Nate Getch
  • 1,479
  • 1
  • 11
  • 8
0

You can't access Session directly in JavaScript.

You can make a hidden field and pass it to your page and then use JavaScript to retrieve the object via document.getElementById