根据另一个选择填充下拉列表

I am trying to populate a drop down list that contains city names based on what country the user selects. This is the country's drop down list:

<select name = "country" onChange = "loadcities(this.value)">
        <?php
            include 'dbconnect.php';
            $query = "SELECT * FROM Country";
            $result = $mysqli->query($query);
            while($row = $result->fetch_array()){
                echo "<option value = '$row[0]'> $row[2] </option>";
            }
        ?>
    </select>

I am using this javascript function to populate it:

function loadcities(selected){
var s = document.getElementById("city");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
            var citynames = (xmlhttp.response).slice();
            for(var i = 0; i < citynames.length(); i++){
                var option = document.createElement(i.toString());
                option.text = citynames[i];
                s.add(option);
            }
        }
    }
    xmlhttp.open("GET", "loadcities.php?q=" + str, true);
    xmlhttp.send();

}

and this is the php file that is used inside the previous function:

<?php
$q = $_REQUEST["q"];
include "dbconnect.php";
$citynames = []; 
$result = $mysqli->query("SELECT cityname from CITY WHERE City.countryid = '$q'");
while($row = $result->fetch_array()){
    $cityname[] = $row[2];
}
echo "$citynames";
?>

I realize there are probably a lot of mistakes, but I have no idea how to fix them. Any help would be appreciated.

First of all in the 3rd code segment you have both $cityname and $citynames. I think they should be the same. Also you are fetching one column from the data base and then using the THIRD column ($row[2]). Probably this should be $row[0].

in the end you are echo-ing an array... that will simply output array and not the array's contents. Also in the 2nd part, in the javascript code, you are using slice() which is used to get a set of values from an array into a new array.

I believe that you should change your 3rd code fragment to:

<?php
$q = $_REQUEST["q"];
include "dbconnect.php";
$result = $mysqli->query("SELECT cityname from CITY WHERE City.countryid = $q");
while($row = $result->fetch_array())
{
    echo $row[0].'@@@@';
}
?>

Then you should change your in your javascript the line that is:

var citynames = (xmlhttp.response).slice();

to

var citynames = (xmlhttp.response).split('@@@@');

As a side note your PHP script has a huge security vulnerability: you are passing $_REQUEST input directly to the database. You should sanitize it before doing so, or you run the risk to get hacked.