I have made a cascade dropdown list for choosing country and city (depending on the country chosen) for users to update their profiles.
In the earlier version where users choose country and city works ok. But since this will be a update profile page, I want to show already selected data if the data is not null.
It works ok for the country selection but couldn't figure out how to implement this already selected data to trigger the javascript because second dropbox only triggered with a selection on the first dropdown.
Any help is appreciated!
Here is the javascript part
<script language="javascript" type="text/javascript">
function getXMLHTTP() { //fuction to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCity(countryId) {
var strURL="findCountry.php?country="+countryId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:
" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
Here is the php part:
<?php
$username = $_SESSION[ 'username' ];
$sql = $conn->query( "SELECT * FROM users WHERE username='$username' " );
if ( $sql->num_rows > 0 ) {
// output data of each row
while ( $info = $sql->fetch_assoc() ) {
echo '
<select id="country" name="country" onchange="getCity(this.value)" required>
<option value="" selected disabled hidden>Country</option>';
$sql2 = $conn->query( "SELECT * FROM world_countries ORDER BY country_name ASC" );
// output data of each row
if ( $info[ 'country' ] != null ) {
echo '<option value="' . $info[ "country" ] . '" selected>' . $info[ "country" ] . '</option>';
}
while ( $row = $sql2->fetch_assoc() ) {
echo '<option value="' . $row[ "cc_iso" ] . '">' . $row[ "country_name" ] . '</option>';
}
echo '<div id="citydiv"><select name="city"><option>Select Country First</option></select></div>';
}}
?>
And here is the findCountry.php:
<?
require_once("config.php");
$country=$_GET['country'];
$sql=$conn->query("SELECT * FROM world_cities WHERE id='$country' ORDER BY full_name_nd ASC");
if ( $sql->num_rows > 0 ) {
echo '
<select name="cities">
<option>Select City</option>';
while($row=$sql->fetch_assoc()) {
echo '<option value="'.$row['full_name_nd'].'">'.$row['full_name_nd'].'</option>';
}
echo '</select>';
} else {
echo 'error';
}
$conn->close();
?>