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.

1

3 Answers 3

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).

Sign up to request clarification or add additional context in comments.

4 Comments

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.
Google has about 12,900,000 results for "ajax tutorials". Pick one.
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,
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.
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>

Comments

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;
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.