简体   繁体   中英

Pass jscolor from one php page to another

I'm using jscolor and trying to pass the users selected color from test1.php to test2.php and then convert to rgb. Somehow is not working.

If I change the form post to test1.php it retrieves the correct value, but when changing action="test2.php" then is not working.

test1.php:

<script>
function update(jscolor) {
    // 'jscolor' instance can be used as a string
    document.getElementById('rect').style.backgroundColor = '#' + jscolor
}
</script>

 <form action="test2.php" method="post">
     Select you favorite color:
     <input name="clr1" class="jscolor {onFineChange:'update(this)'}">
     <input type="submit" name="submit">
 </form>
 <p id="rect" style="border:1px solid gray; width:161px; height:100px;">

<?php 
  session_start();

  if(isset($_POST['clr1'])) { 
      $selected_color = $_POST['clr1']; 
      $_SESSION['bgcolors'] = $selected_color;
  }
?>

test2.php:

session_start();
$selected_color = $_SESSION['bgcolors'];
echo $selected_color;
echo "<br>";
list($r, $g, $b) = array_map('hexdec', str_split($selected_color, 2));

$bgcolor2 = $r . "," . $g . "," .$b;
echo $bgcolor2;

Add in test2.php after session_start this code

 if (isset($_POST['clr1'])) { 
    $selected_color = $_POST['clr1']; 
    $_SESSION['bgcolors'] = $selected_color;
 }

In php page 2 you are going to want to retrieve the variable by starting the session with session_start and after that you can access it with $_SESSION['bgcolors']

However I can see a problem with your code in that you are not calling session_start the first think you do.

Always call session_start unconditionally. Always call session_start before you output anything on the page.

As seen in this stack response What is proper way to calling session_start()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM