Iam trying to make a dropdown select "sticky", basically I need to retain the value of the dropdown select in a session variable, then use the session variable in the doprdown select, so that when the page is refreshed, the value is retained in the dropdown select. I am trying to do this in php.
Here is the code for the select :
<?php
$countryId = isset($_POST['country']) ? $_POST['country'] : '';
asort($dirs);
reset($dirs);
echo '<option value="" disabled selected>Select Your Country</option>';
foreach ($dirs as $p => $w):
$selected = $countryId === $w ? 'selected' : '';
echo '<option value="' . $w . '" ' . $selected . '>' . $w . '</option>';
endforeach;
?>
Any advice is greatly appreciated
make a second file called savesession.php
<?php
if (isset($_GET['country_option'])) $_SESSION['country_option'] = $_GET['country_option'];
then change your code to be
<?php
$countryId = isset($_POST['country']) ? $_POST['country'] : isset($_SESSION['country_option']) ? $_SESSION['country_option'] : '';
asort($dirs);
reset($dirs);
echo '<option value="" disabled selected>Select Your Country</option>';
foreach($dirs as $p => $w):
$selected = $countryId===$w ? 'selected' : '';
echo '<option value="'.$w.'" '.$selected.'>'.$w.'</option>';
endforeach;
?>
<script>
function onDropDownChange(){
var dd = document.getElementById("dropdownID");
var selectedItem = dd.options[dd.selectedIndex].value;
var ajax = new XMLHttpRequest();
ajax.open("GET", "yourpage.com/savesession.php?country_option=" + selectedItem, true);
ajax.send();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
}
}
}
</script>
then add an onchange="onDropDownChange"
and id="dropdownID"
to the <select>
so that it calls a javascript function onDropDownChange