0

Why I do not get any printing on the screen (m1, m2 or m3)?

i.e. how can I pass JavaScript var to PHP Session.

<?php session_start(); ?>

<html>
<head>

<script type="text/javascript">
function disp_text()
   {
      var p = document.myform.mylist.value;
      <?php $_SESSION['color'] ?> = p;
      <?php echo $_SESSION['color'] ?>;
   }
</script>

</head>
<body>

<FORM NAME="myform">
<SELECT NAME="mylist" onChange="disp_text()">
<OPTION VALUE="m1">Red
<OPTION VALUE="m2">Blue
<OPTION VALUE="m3">Green
</SELECT>
</FORM>

Thanks for any help.

blsn
  • 1,077
  • 3
  • 18
  • 38

3 Answers3

5

And another one for the count... JavaScript runs on the user's computer, PHP runs on the server. View the page source (right-click, View Source) and you will see exactly why it doesn't work:

<script type="text/javascript">
function disp_text()
   {
      var p = document.myform.mylist.value;
      = p;
      ;
   }
</script>

The only way to get JS variables into PHP is via a form (which I am using loosely to include AJAX).

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • I’m not familiar with Ajax. Could you please give a small tip of how do I get this done (via a form). Thanks again. – blsn Jun 30 '12 at 14:47
  • Google has about 12,900,000 results for "ajax tutorials". Pick one. – Niet the Dark Absol Jun 30 '12 at 14:51
  • Thank you all for your support, but I thought to get here a simple answer to a simple question which is related to PHP and Javascript. I didn’t except an answer of go study Ajax. I would appreciate it, if anybody has a solution for me with PHP and Javascript, – blsn Jun 30 '12 at 15:04
  • PHP can pass whatever it wants to JavaScript, because it runs before the JS does. However, to get JS stuff back into PHP you have to use AJAX. – Niet the Dark Absol Jun 30 '12 at 15:06
0

Try this

<html>
<head>
<script type="text/javascript">
function disp_text()
   {
      var e = document.getElementsByName("mylist")[0];
      var p = e.options[e.selectedIndex].value;
      sessionStorage.color = p;
      document.write(p);
   }
</script>
</head>
<body>
<FORM NAME="myform">
<SELECT NAME="mylist" onChange="disp_text()">
<OPTION VALUE="m1">Red</OPTION>
<OPTION VALUE="m2">Blue</OPTION>
<OPTION VALUE="m3">Green</OPTION>
</SELECT>
</FORM>
</body>
</html>
User
  • 752
  • 5
  • 11
0

index.php:

<script type="text/javascript">
    var time = "OK then, let's do this!";
    sessionStorage.setItem("time", time);
    window.location.href = "test.php";
</script>

test.php

<script type="text/javascript">
    var time = sessionStorage.getItem("time");
    console.log(time);
    <?php $abc = "<script>document.write(time)</script>"?> 
</script>

<?php
    echo $abc;
?>
Marvin Fischer
  • 2,552
  • 3
  • 23
  • 34