I have two select options of Countries and States. The option values are populating from database using php functions. I would like to populate the States depending on the selection of Countries. For example, if I select US from Countries then States select option will populate me all the States belongs to the US Country.
Here is my code -
<select id="countryName" name="countryName" onChange="getCountryCode()">
<option value=""></option>
<?php $countries = $location->getCountries();
foreach ($countries as $country) {
echo '<option value="' . $country->id . '">' . $country->name . '</option>';
}
?>
</select>
I can get the selected country value using javascript function
<script type="text/javascript">
function getCountryCode(){
var countryCode = document.getElementById('countryName').value;
}
</script>
After all these, I am trying to get the States of selected Country using the php function getStates($countryCode). But I don't know how to pass the javascript variable to php function.
<select name="stateName">
<option value=""></option>
<?php $states = $location->getStates($countryCode);
foreach ($states as $state) {
echo '<option value="' . $state->id . '">' . $state->name . '</option>';
}
?>
</select>
Does anyone have any idea how do I pass the javascript variable to php or if have better idea than this, please do share.
Thank you!