简体   繁体   中英

Updating session variable using onclick in php

I am trying to update the $_SESSION['state'] whenever the user clicks on the anchor tag by firing the onclick event. The variable $state_names_array as all the names of the states of a specific country. But problem is that no matter whichever of the anchor tag I click on, the $_SESSION['state'] is always getting updated by the last element of the $state_names_array.

<?php
foreach($state_names_array as $value){
    $temp = '<?php $_SESSION["state"]=$value;?>';
    ?>
    <a href="index.php" onclick="document.write('<?php $_SESSION['state'] = $value ?>')"><?php echo $value ?></a><br>
    <?php
}
?>

I will not code whole code, I will just show you an example, how to do it:

<?php
    foreach ($state_names_array as $value) {
        echo '<a href="index.php" onclick="change_value('.$value.');">'.$value.'</a><br>';
    }
 ?>

Then you will have javascript function change_value :

here you will send ajax call to some PHP file, where you will process $_SESSION["state"]=$value;

Also you didnt say, what you want after anchor is clicked, because you will be able to access new $_SESSION["state"] only after refreshing your site...

Also maybe you just want to redirect to index.php, after clicking on some anchor, and that will be enough for you, then just use value as $_GET parameter, fe:

<?php
    foreach ($state_names_array as $value) {
        echo '<a href="index.php?new_value='.$value.'">'.$value.'</a><br>';
    }
?>

and add to you index.php file this lines:

if (isset($_GET['new_value'])) {
    $_SESSION["state"] = $_GET['new_value'];
}

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