Samuel del Rio Samuel del Rio - 6 months ago 7
PHP Question

How to get in a variable the value of the selection of a Select/Drop Down Menu PHP or HTML

I'm trying to connect 2 drop-downs so in the first I show a list of countries and based on the selection of the country I show a list of the cities for the country selected.

I have my index.php file which load all the countries correctly as seen in this image:

enter image description here

Code to load my countries

<select name="country" id="country">
<?php
$db = pg_connect("$db_host $db_name $db_username $db_password");
$query = "SELECT country FROM countries";

$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}

printf ("<option value=Select>Select a Country</option>");
while($myrow = pg_fetch_assoc($result)) {
printf ("<option value=$myrow[country]>$myrow[country]</option>");
}
?>
</select>


Now I'm trying to do the same based on the selection from the previous "Select" but it is not working. The issue I'm having is getting the value selected in the country select because if I hard-type a value of a country like: $query = "SELECT city FROM cities where country = Albania"; then it works. Also I tried to print the value of the country selected: (echo $selectedCountry;) and it not printing anything so I'm guessing neither $selectedCountry = $_GET['country']; or $selectedCountry = $_POST['country']; are getting the value of the country selected.

<select name="city" id="city">
<?php
$db = pg_connect("$db_host $db_name $db_username $db_password");

$selectedCountry = $_GET['country'];
$selectedCountry = $_POST['country'];
echo $selectedCountry;

$query = "SELECT city FROM cities where country = ' $selectedCountry '";

$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
printf ("<option value=Select>Select a City</option>");
while($myrow = pg_fetch_assoc($result)) {
printf ("<option value=$myrow[city]>$myrow[city]</option>");
}
?>
</select>


Thank you very much in advance

UPDATE

This is what I see in the first Load. Where the country Select is loaded with all the values as per the image above and the city Select is empty (Only the "Select a city" value) waiting to be loaded with the values depending on the country selection.

enter image description here

LAST UPDATE

Here is the code for my form: Country and City are the same but now I call onChange="getCity(this.value)" from the country select:

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

<select name="country" id="country" onChange="getCity(this.value)">
<?php
$db = pg_connect("$db_host $db_name $db_username $db_password");
$query = "SELECT country FROM countries";

$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}

printf ("<option value=Select>Select a Country</option>");
while($myrow = pg_fetch_assoc($result)) {

printf ("<option value=$myrow[country]>$myrow[country]</option>");
}
?>

</select>
<span class="error">* <?php echo $countryErr;?></span>
<br>

<div id="citydiv">
<select name="city" id="city"><option>Select City</option></select>
</div>

<div id="querydiv">
</div>
<input type="submit" name="submit" value="SIGN UP">
</form>


and here is my script code:

<script language="javascript" type="text/javascript">
function getCity(countryId) {
$(function() {

var query = '<br><br><br><br>SELECT city FROM cities where country = ' + countryId;
var str = '<select name="city" id="city"><?php $query = "SELECT city FROM cities where country = 'Spain'";$result = pg_query($query); if (!$result) {echo "Problem with query " . $query . "<br/>";echo pg_last_error();exit();}printf ("<option value=Select>Select a City</option>");while($myrow = pg_fetch_assoc($result)) {printf ("<option value=$myrow[city]>$myrow[city]</option>");}?></select>';


document.getElementById('citydiv').innerHTML= str;
document.getElementById('querydiv').innerHTML= query;
});
}
</script>


so the querydiv prints the country selected --> GOOD THIS IS WHAT I WANT
the citydiv prints the cities for Spain which is the country I hard-typed in the str var. --> GOOD THIS IS WHAT I WANT

Now if I try to change the hard-typed country for the "countryId" does not work:

var str = '<select name="city" id="city"><?php $query = "SELECT city FROM cities where
country = 'countryID'";$result = pg_query($query); if (!$result) {echo "Problem with query "
. $query . "<br/>";echo pg_last_error();exit();}printf ("<option value=Select>
Select a City</option>");while($myrow = pg_fetch_assoc($result)) {printf
("<option value=$myrow[city]>$myrow[city]</option>");}?></select>';


I also tried and didn't work either:

country = ' + countryID + '"

country = ' + countryID '"

Thanks again

Answer

Well, what you really need is AJAX call which allows you to communicate with server without reloading a page. All you have to do is basically send a new HTTP request with a country parameter to get the list of cities in it. The correct way would be to send (HTTP response) only the data(cities) in JSON or similar format, and not its presentation also (html), but for simplicity, you can continue to work like you started (return data with html).

Start by separating the code that generates HTML selectBoxOptions of cities in another script. You will use that script to get the list of cities in particular country by using AJAX (XMLHttpRequest library).

Have a look at this, it's a working solution of your problem. HTTP request is sent when user change the select box option, that way your cities select box gets updated every time it needs. All you have to do is change the url in the onchange attribute that points to your script (I previously said that you should move 2nd block of code into separate script).

<!DOCTYPE html>
<html>
<head>

    <script>
        function populateCities(citiesSelectBoxOptions){
            document.getElementById("city").innerHTML = citiesSelectBoxOptions;
        }

        function httpGetAsync(theUrl, callback)
        {
            alert(theUrl);
            var xmlHttp = new XMLHttpRequest();
            xmlHttp.onreadystatechange = function() {
                if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
                    callback(xmlHttp.responseText);
            }
            xmlHttp.open("GET", theUrl, true); // true for asynchronous
            xmlHttp.send(null);
        }
    </script>
</head>
<body>


<select name="country" id="country" onchange="httpGetAsync('www.yourdomain.com/getCities?country=' + this.options[this.selectedIndex].value, populateCities)">
    <option value="Country1">Country 1</option>
    <option value="Country2">Country 2</option>
</select>

<select name="city" id="city">

</select>

</body>
</html>

getCities.php

<?php

$db = pg_connect("$db_host $db_name $db_username $db_password");

$selectedCountry = $_GET['country'];

$query = "SELECT city FROM cities where country = ' $selectedCountry '";

$result = pg_query($query);
if (!$result) {
    echo "Problem with query " . $query . "<br/>";
    echo pg_last_error();
    exit();
}
printf ("<option value='Select'>Select a City</option>");
while($myrow = pg_fetch_assoc($result)) {
    printf ("<option value='$myrow[city]'>$myrow[city]</option>");
}
?>
Comments